C++ 中不区分大小写的标准字符串比较

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23943728/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 00:35:37  来源:igfitidea点击:

Case insensitive standard string comparison in C++

c++stringsubstr

提问by Santhosh Kumar

void
main()
{
    std::string str1 = "abracadabra";
    std::string str2 = "AbRaCaDaBra";

    if (!str1.compare(str2)) {
        cout << "Compares"
    }
}

How can I make this work? Bascially make the above case insensitive. Related question I Googled and here

我怎样才能使这项工作?基本上使上述大小写不敏感。相关问题我在谷歌上搜索过

http://msdn.microsoft.com/en-us/library/zkcaxw5y.aspx

http://msdn.microsoft.com/en-us/library/zkcaxw5y.aspx

there is a case insensitive method String::Compare(str1, str2, Bool). Question is how is that related to the way I am doing.

有一个不区分大小写的方法 String::Compare(str1, str2, Bool)。问题是这与我的工作方式有什么关系。

回答by 0x499602D2

You can create a predicate function and use it in std::equalsto perform the comparison:

您可以创建一个谓词函数并使用它std::equals来执行比较:

bool icompare_pred(unsigned char a, unsigned char b)
{
    return std::tolower(a) == std::tolower(b);
}

bool icompare(std::string const& a, std::string const& b)
{
    if (a.length()==b.length()) {
        return std::equal(b.begin(), b.end(),
                           a.begin(), icompare_pred);
    }
    else {
        return false;
    }
}

Now you can simply do:

现在你可以简单地做:

if (icompare(str1, str)) {
    std::cout << "Compares" << std::endl;
}

回答by Andro

Covert both to lower case and then compare them.

将两者都转换为小写,然后比较它们。

Converting to lower:

转换为较低:

for(int i = 0; i < str1.size(); i++)
{
  str[i] = tolower(str[i]);
}

Comparing strings:

比较字符串:

if (str1.compare(str2) == 0) { ... }

A zero value indicates that both strings are equal.

零值表示两个字符串相等。

EDIT

编辑

This can be used to avoid for loop: http://www.cplusplus.com/reference/algorithm/transform/

这可以用来避免循环:http: //www.cplusplus.com/reference/algorithm/transform/

std::transform(in.begin(),in.end(),std::back_inserter(out),tolower);