问题
This question already has an answer here:
- Case-insensitive string comparison in C++ [closed] 31 answers
I know there are ways to do case ignore comparison that involve iterating through strings or one good one on SO needs another library. I need to put this on other computers that might not have it installed. Is there a way to use the standard libraries to do this? Right now I am just doing...
if (foo == "Bar" || foo == "bar")
{
cout << "foo is bar" << endl;
}
else if (foo == "Stack Overflow" || foo == "stack Overflow" || foo == "Stack overflow" || foo == "etc.")
{
cout << "I am too lazy to do the whole thing..." << endl;
}
This could drastically improve the readability and usability of my code. Thanks for reading this far.
回答1:
strncasecmp
The
strcasecmp()
function performs a byte-by-byte comparison of the strings s1 and s2, ignoring the case of the characters. It returns an integer less than, equal to, or greater than zero if s1 is found, respectively, to be less than, to match, or be greater than s2.The
strncasecmp()
function is similar, except that it compares no more than n bytes of s1 and s2...
回答2:
usually what I do is just compare a lower-cased version of the string in question, like:
if (foo.make_this_lowercase_somehow() == "stack overflow") {
// be happy
}
I believe boost has built-in lowercase conversions, so:
#include <boost/algorithm/string.hpp>
if (boost::algorithm::to_lower(str) == "stack overflow") {
//happy time
}
回答3:
why don't you you make everything lower case and then compare?
tolower()
int counter = 0;
char str[]="HeLlO wOrLd.\n";
char c;
while (str[counter]) {
c = str[counter];
str[counter] = tolower(c);
counter++;
}
printf("%s\n", str);
回答4:
You can write a simple function to convert the existing string to lower case as follows:
#include <string>
#include <ctype.h>
#include <algorithm>
#include <iterator>
#include <iostream>
std::string make_lowercase( const std::string& in )
{
std::string out;
std::transform( in.begin(), in.end(), std::back_inserter( out ), ::tolower );
return out;
}
int main()
{
if( make_lowercase( "Hello, World!" ) == std::string( "hello, world!" ) ) {
std::cout << "match found" << std::endl;
}
return 0;
}
回答5:
I just wrote this, maybe it can be useful to somebody:
int charDiff(char c1, char c2)
{
if ( tolower(c1) < tolower(c2) ) return -1;
if ( tolower(c1) == tolower(c2) ) return 0;
return 1;
}
int stringCompare(const string& str1, const string& str2)
{
int diff = 0;
int size = std::min(str1.size(), str2.size());
for (size_t idx = 0; idx < size && diff == 0; ++idx)
{
diff += charDiff(str1[idx], str2[idx]);
}
if ( diff != 0 ) return diff;
if ( str2.length() == str1.length() ) return 0;
if ( str2.length() > str1.length() ) return 1;
return -1;
}
来源:https://stackoverflow.com/questions/9182912/case-insensitive-string-comparison-c