How would I compare two strings in C++ case insensitively?
Undead Wizard
2011-06-10 12:21:27 UTC
In Java you can use x.equalsIgnoreCase("y") to compare two strings without taking into account the case of either one. How would you do so in C++?
Four answers:
Nate
2011-06-10 12:44:35 UTC
They way I do it is by using the tolower() function to convert all uppercase characters to lowercase before comparing. So if your strings are in the form of char arrays, you could write a function like this:
BOOL bMatches(char* string1, char* string2) {
for(i=0;i<=strlen(string1);i++) //use "<=" to include the null terminator, in case string2 is longer
{
if(tolower(string1[i]) != tolower(string2[i])) //convert each character to lowercase, then compare
return FALSE; //strings don't match if comparison fails
}
return TRUE; //if for loop completes, then strings match
}
Charmaine
2016-05-14 17:03:34 UTC
Your question is pretty vague like " I tried c_str(), but that makes all the slots of book[] equal to the user inputted string no matter what they are.", I'll try my best anyways . Suppose you got two std::string objects a,b ; your option 1 is to use boost string algorithms library : #include #include std::string a= "Hello"; std::string b= "hEllO"; boost::iequals(a, b) == true ; option 2: You'll have to bang your head creating your own char traits like std::char_traits which does the right char comparison , and use it on like std::basic_string a = "hello", b = "HellO"; and simply "a==b" will do the right thing. option 3: Compare corresponding chars in both strings using std::toupper/std::tolower residing in I believe etc e.g sample function algo could be : bool compareString(const string& a, const string& b) { if(a.length() != b.length()) { a and b are not string of same length; return false; } for loop (i to a.lenth() ) { if( std::toupper(a[i]) != std::toupper(b[i]) ) { return false; } } return true; }
GammaFunction
2011-06-10 13:02:29 UTC
Those first 2 answers might be more general than what you need.
If you just want to treat "Y" as the same as "y" you can do that with a simple logical:
then let's say you want to compare x and get true if it's Y or y
( x == "Y" || x == "y" )
That logical expression will be true iff x is Y or x is y
wasi
2011-06-10 12:45:49 UTC
The Boost.String library has an algorithm for doing case-insenstive comparisons among others.
#include
std::string str1 = "hello, world!";
std::string str2 = "HELLO, WORLD!";
if (boost::iequals(str1, str2))
{
// Reaches here if the strings are identical
}
By this method you need not convert strings to all lower case or upper case and then compare
ⓘ
This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.