Comparing strings with case insensitive in C ++

void main() { std::string str1 = "abracadabra"; std::string str2 = "AbRaCaDaBra"; if (!str1.compare(str2)) { cout << "Compares" } } 

How can I do this job? Basically make the above case insensitive. Related Question I'm Googled and Here

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

there is a case-insensitive String :: Compare method (str1, str2, Bool). The question is how this relates to how I do it.

+6
source share
2 answers

You can create a predicate function and use it in std::equals to compare:

 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:

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

Hide and lowercase, and then compare them.

Convert to lower:

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

String Comparison:

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

A zero value indicates that both lines are equal.

EDIT

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

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

Source: https://habr.com/ru/post/970060/


All Articles