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:
="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)
//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
size_t size1=s1.size(), size2=s2.size();// cache lengths
//return -1,0 or 1 according to strings' lengths
return (size1<size2) ? -1 : 1;
Test this function:
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.