C ++中不区分大小写的标准字符串比较 [英] Case insensitive standard string comparison in C++

查看:836
本文介绍了C ++中不区分大小写的标准字符串比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

如何使这项工作? Bascally使上述情况不敏感。相关问题
I Googled and Here

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

有一个不区分大小写的方法String :: Compare( str1,str2,Bool)。问题是如何与我的方式相关。

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

推荐答案

您可以创建一个谓词函数,并在 std :: equals 执行比较:

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

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
    }
}


b $ b

现在你可以简单地做:

Now you can simply do:

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

这篇关于C ++中不区分大小写的标准字符串比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆