I know for C++ that basic comparative operators can accomplish the task if both words are either entirely lower or entirely upper case. I have an array of strings and letter
Yes there is a case insensitive way to compare strings in C++. The key is that std::string
is a template:
template ,
class Allocator = allocator>
class basic_string;
The traits
here control how the charT
's relate to each other. For normal std::string
, they do what you'd expect, but we can just write our own traits that are case insensitive:
struct case_insensitive_traits
: char_traits
{
static bool eq(char a, char b) { return tolower(a) == tolower(b); }
static bool ne(char a, char b) { return !eq(a, b); }
static bool lt(char a, char b) { return tolower(a) < tolower(b); }
static bool gt(char a, char b) { return tolower(a) > tolower(b); }
static int compare(const char* a, const char* b, size_t n)
{
for (size_t i = 0; i < n; ++i) {
int delta = tolower(a[i]) - tolower(b[i]);
if (delta != 0) return delta;
}
return 0;
}
static const char* find(const char* s, size_t n, char c)
{
c = tolower(c);
for (size_t i = 0; i < n; ++i, ++s) {
if (tolower(*s) == c) return s;
}
return nullptr;
}
};
With that:
using case_insensitive_string = std::basic_string;
case_insensitive_string a{"hello"};
case_insensitive_string b{"hElLo"};
assert(a == b);