尝试使用以下方法比较字符串:
!(stringvector[i]).compare(vector[j][k])
仅适用于某些条目
vector[j][k]
——即区分大小写的字符串匹配。
如何通过此功能获得不区分大小写的匹配?
这是我正在编写的一些代码
#include <iostream>
#include <vector>
#include <string>
using namespace std; //poor form
vector<string> stringvector = {"Yo", "YO", "babbybabby"};
vector<string> vec1 = {"yo", "Yo" , "these"};
vector<string> vec2 = {"these", "checked" , "too" , "Yo", "babbybabby"};
vector<vector<string>> vvs = {vec1, vec2};
for (int v = 0; v < vvs.size(); v++) //first index of vector
{
for(int s = 0; s < vvs[v].size(); s++) //second index of vector
{
for(int w = 0; w < stringvector.size(); w++)
{
if (stringvector[w] == vvs[v][s])
{cout << "******FOUND******";}
}
}
}
对于不区分大小写的匹配,这不会打印出 FOUND。
Stringvector[w] == vvs[v][s] 不进行不区分大小写的比较,有没有办法轻松添加此功能?
--D教授
最佳答案
tl;博士
使用 ICU library .
当涉及到自然语言字符串时,“简单的方法”通常充满了问题。
正如我在 my answer 中指出的那样对于 @Armando 链接到的“小写转换”答案,如果您想真正做到正确,那么您目前最好使用 ICU library ,因为此时标准中没有任何内容为您提供实际 Unicode 支持。
如果你看the docs到 @NutCracker 使用的 std::tolower
,你会发现...
Only 1:1 character mapping can be performed by this function, e.g. the Greek uppercase letter 'Σ' has two lowercase forms, depending on the position in a word: 'σ' and 'ς'. A call to std::tolower cannot be used to obtain the correct lowercase form in this case.
如果您想正确做到这一点,您需要完整的 Unicode 支持,这意味着 ICU 库,直到 C++ 标准的后续修订版实际上将其引入到标准库。
使用icu::UnicodeString
-- 虽然一开始可能很笨重 -- 存储语言字符串可以让您访问 caseCompare()
,它会进行正确的不区分大小写的比较。
关于c++ - 比较字符串不区分大小写的简单方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42269820/