4.13. Doing a Case-Insensitive String Comparison
Problem
You have two strings, and you want to know if they are equal, regardless of the case of the characters. For example, “cat” is not equal to “dog,” but “Cat,” for your purposes, is equal to “cat,” “CAT,” or “caT.”
Solution
Compare the strings using the equal standard
algorithm (defined in <algorithm>), and supply
your own comparison function that uses the toupper
function in <cctype> (or towupper in <cwctype> for wide
characters) to compare the uppercase versions of characters. Example 4-21 offers a generic solution. It
also demonstrates the use and flexibility of the STL; see the discussion below for a full
explanation.
Example 4-21. Case-insensitive string comparison
1 #include <string> 2 #include <iostream> 3 #include <algorithm> 4 #include <cctype> 5 #include <cwctype> 6 7 using namespace std; 8 9 inline bool caseInsCharCompareN(char a, char b) { 10 return(toupper(a) == toupper(b)); 11 } 12 13 inline bool caseInsCharCompareW(wchar_t a, wchar_t b) { 14 return(towupper(a) == towupper(b)); 15 } 16 17 bool caseInsCompare(const string& s1, const string& s2) { 18 return((s1.size() == s2.size()) && 19 equal(s1.begin(), s1.end(), s2.begin(), caseInsCharCompareN)); 20 } 21 22 bool caseInsCompare(const wstring& s1, const wstring& s2) { 23 return((s1.size() == s2.size()) && 24 equal(s1.begin(), s1.end(), s2.begin(), caseInsCharCompareW)); 25 } 26 27 int main() { 28 string s1 = "In the BEGINNING..."; 29 string s2 = "In the beginning..."; ...