How to do case insensitive string comparison?
The simplest way to do it (if you're not worried about special Unicode characters) is to call toUpperCase
:
var areEqual = string1.toUpperCase() === string2.toUpperCase();
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 do I do a case-insensitive string comparison?
Assuming ASCII strings:
string1 = 'Hello'
string2 = 'hello'
if string1.lower() == string2.lower():
print("The strings are the same (case insensitive)")
else:
print("The strings are NOT the same (case insensitive)")
As of Python 3.3, casefold() is a better alternative:
string1 = 'Hello'
string2 = 'hello'
if string1.casefold() == string2.casefold():
print("The strings are the same (case insensitive)")
else:
print("The strings are NOT the same (case insensitive)")
If you want a more comprehensive solution that handles more complex unicode comparisons, see other answers.
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;
}
Related Topics
What's the Difference Between '$(This)' and 'This'
How to Work Around JavaScript'S Parseint Octal Behavior
Modifying a Copy of a JavaScript Object Is Causing the Original Object to Change
How to Detect Idle Time in JavaScript
Executing ≪Script≫ Elements Inserted With .Innerhtml
How to Get a Subset of a JavaScript Object'S Properties
Why Does Changing an Array in JavaScript Affect Copies of the Array
How to Detect If Multiple Keys Are Pressed At Once Using JavaScript
How to Pass Props to {This.Props.Children}
Should All Jquery Events Be Bound to $(Document)
How Does "This" Keyword Work Within a Function
JavaScript Get Clipboard Data on Paste Event (Cross Browser)
Asp.Net MVC Jsonresult Date Format
How to Check If an Element Is Hidden in Jquery
How to Export JavaScript Array Info to CSV (On Client Side)