Skip to Main Content
C++ Cookbook
book

C++ Cookbook

by D. Ryan Stephens, Christopher Diggins, Jonathan Turkanis, Jeff Cogswell
November 2005
Beginner to intermediate content levelBeginner to intermediate
594 pages
16h 23m
English
O'Reilly Media, Inc.
Content preview from C++ Cookbook

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..."; ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C++ System Programming Cookbook

C++ System Programming Cookbook

Onorato Vaticone

Publisher Resources

ISBN: 0596007612Supplemental ContentErrata Page