Browse DevX
Sign up for e-mail newsletters from DevX


String Manipulation Made Easy with std::string Algorithms-2 : Page 2




Building the Right Environment to Support AI, Machine Learning and Deep Learning

Case Insensitive Comparisons
The overloaded == operator of std::string performs a case-sensitive lexicographical comparison. This feature is useful in implementing IDEs of case-sensitive programming languages such as C++. However, there are situations in which you need a case-insensitive comparison. Suppose you need to locate all of the occurrences of a certain word in a document:

string Evita_lyrics ="Mourning all day and mourning all night";

A common technique for eliminating case differences is transforming the entire string to uppercase letters. However, this approach is ruled out if the original string must remain intact. Alternatively, you can let the comparison function locally convert each letter to its uppercase counterpart as shown in the following code listing:

int nocase_cmp(const string & s1, const string& s2) { string::const_iterator it1=s1.begin(); string::const_iterator it2=s2.begin(); //stop when either string's end has been reached while ( (it1!=s1.end()) && (it2!=s2.end()) ) { if(::toupper(*it1) != ::toupper(*it2)) //letters differ? // return -1 to indicate smaller than, 1 otherwise return (::toupper(*it1) < ::toupper(*it2)) ? -1 : 1; //proceed to the next character in each string ++it1; ++it2; } size_t size1=s1.size(), size2=s2.size();// cache lengths //return -1,0 or 1 according to strings' lengths if (size1==size2) return 0; return (size1<size2) ? -1 : 1; }

Test this function:

string s1="Mourning"; string s2="mourning"; int n=nocase_cmp(s1, s2); //n=0

As expected, the result is 0 indicating that the strings are identical is spite of the case difference of their initial letter.

Author's Note: Don't be tempted to hide the nocase_cmp() function in an overloaded == as this will clash with the standard (and case-sensitive) == operator.

Thanks for your registration, follow us on our social networks to keep up-to-date