Case insensitive standard string comparison in C++

Santhosh Kumar picture Santhosh Kumar · May 29, 2014 · Viewed 55.6k times · Source
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

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

Answer

0x499602D2 picture 0x499602D2 · May 30, 2014

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

Now you can simply do:

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