Case-insensitive string comparison in C++
Boost includes a handy algorithm for this:
#include <boost/algorithm/string.hpp>
// Or, for fewer header dependencies:
//#include <boost/algorithm/string/predicate.hpp>
std::string str1 = "hello, world!";
std::string str2 = "HELLO, WORLD!";
if (boost::iequals(str1, str2))
{
// Strings are identical
}
How to do a case-insensitive string comparison?
If you can afford deviating a little from strict C
standard, you can make use of strcasecmp()
.
It is a POSIX API.
Otherwise, you always have the option to convert the strings to a certain case (UPPER or lower) and then perform the normal comparison using strcmp()
.
Case insensitive standard string comparison in C++
You can create a predicate function and use it in std::equals
to perform the comparison:
bool icompare_pred(unsigned char a, unsigned char b)
{
return std::tolower(a) == std::tolower(b);
}
bool icompare(std::string const& a, std::string const& b)
{
if (a.length()==b.length()) {
return std::equal(b.begin(), b.end(),
a.begin(), icompare_pred);
}
else {
return false;
}
}
Now you can simply do:
if (icompare(str1, str)) {
std::cout << "Compares" << std::endl;
}
Case insensitive string comparison C++
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...
Related Topics
Statically Declared 2-D Array C++ as Data Member of a Class
Inlining Failed in Call to Always_Inline '_M256D _Mm256_Broadcast_Sd(Const Double*)'
Waitforinputidle Doesn't Work for Starting Mspaint Programmatically
What Happens When a Computer Program Runs
Is There a Working C++ Refactoring Tool
.C VS .Cc VS. .Cpp VS .Hpp VS .H VS .Cxx
5 Years Later, Is There Something Better Than the "Fastest Possible C++ Delegates"
Compile a Dll in C/C++, Then Call It from Another Program
Std::String Length() and Size() Member Functions
Can Lambda Functions Be Templated
Visual Studio Code Formatting for "{ }"
How to Use Createthread for Functions Which Are Class Members
How to Return in Void Function
How to Read from a Version Resource in Visual C++