Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Case insensitive standard string comparison in C++ [duplicate]

Tags:

c++

string

substr

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.

like image 553
Santhosh Kumar Avatar asked May 29 '14 21:05

Santhosh Kumar


People also ask

How do you compare two string cases insensitive?

Comparing strings in a case insensitive manner means to compare them without taking care of the uppercase and lowercase letters. To perform this operation the most preferred method is to use either toUpperCase() or toLowerCase() function. toUpperCase() function: The str.

Is string compare case-sensitive in C?

stringCmp() - Compares two strings (case sensitive).

Can I use == to compare strings in C?

You can't compare strings in C with ==, because the C compiler does not really have a clue about strings beyond a string-literal.

Are string comparisons case-sensitive?

operators differs from string comparison using the String. CompareTo and Compare(String, String) methods. They all perform a case-sensitive comparison.


1 Answers

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;
}
like image 195
David G Avatar answered Oct 06 '22 00:10

David G