c++ toupper() 比较两个字符串

标签 c++ string toupper

我已经创建了一组算法,它接受一个字符串 vector 的输入,检查是否有任何字符串出现不止一次:如果是这样,从 vector 中删除所有额外出现的字符串,然后输出新的,'lighter ' 没有冗余的数组。

它工作得很好,只是现在我要让它不区分大小写;我试图简单地将 toupper() std 函数添加到 == 比较语句,但它似乎不起作用。

我对 Java 有更熟悉的背景,正在尝试学习 C++。
有人可以告诉我如何更正我的语法吗?

// Output old list.
cout << endl << "==========\nOld list:\n==========";
for (int i = 0; i < count; i++) {
    cout << endl << list[i];
}
cout << endl << endl;

// Check uniqueness.
for (int i = 0; i < count; i++)
    for (int j = i+1; j < count; j++) {
        if (toupper(list[i]) == toupper(list[j])) {
            list[j] = "";
            count--;
        }
    }

// Output new list.
cout << endl << "==========\nNew list:\n==========";
for (int i = 0; i < count; i++) {
    cout << endl << list[i];
}
cout << endl << endl;

最佳答案

你的循环在 list array vector 中留下了 “holes”,但是 array vector 的大小不会改变(但你减少了上限 count)

可能还有许多其他选择,但如果您不想对其进行太多修改,您可能需要在一个附加循环中从 复制非空元素list 数组到一个新的数组中

编辑:整合部分答案

首先我们要有一个函数来执行 toUpper(这是从@Jim22150 修改的)

std::string stringToUpper(const std::string &input) {
    std::string toBeModified=input;
    std::transform(toBeModified.begin(), toBeModified.end(), toBeModified.begin(), ::toupper);
    return toBeModified;
}

现在,我们不能留下洞,所以我们应该使用删除(正如@Scott Christopher Stauffe 指出的那样):

// Output old list.
cout << endl << "==========\nOld list:\n==========";
for (int i = 0; i < count; i++) {
    cout << endl << list[i];
}
cout << endl << endl;

// Check uniqueness.
for (int i = 0; i < count; i++)
    for (int j = i + 1; j < count; j++) {
        if(stringToUpper(list[i]) == stringToUpper(list[j])) {
            list.erase(j,1);
            count--;
        }
    }
}

// Output new list.
cout << endl << "==========\nNew list:\n==========";
for (int i = 0; i < count; i++) {
    cout << endl << newlist[i];
}
cout << endl << endl;

关于c++ toupper() 比较两个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22722123/

相关文章:

c++ - C++中的非阻塞线程安全队列?

c++ - string::string 构造函数中的奇怪 "Bus error"

c++ - 如何创建 CMakeLists.txt 以编译 PNaCI 程序?

c - 为什么我的函数只破坏了一个字符数组?

coding-style - 比较大写或小写是否更常见/标准?

c++ - rpc 和普通 tcp/udp 服务器客户端程序的区别?

string - 施放 NSString!快速字符串

arrays - 使用嵌套填充创建二维字符串数组

C中转换为全部大写字母的bug

function - Haskell-ghci,找不到函数 toUpper?