Yes, there is a random way to compare strings in C ++. The key is that std::string is a template:
template <class charT, class traits = char_traits<charT>, class Allocator = allocator<charT>> class basic_string;
Here, traits control how charT relate to each other. For a normal std::string they do what you expect, but we can just write our own traits that are case insensitive:
struct case_insensitive_traits : char_traits<char> { 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 this:
using case_insensitive_string = std::basic_string<char, case_insensitive_traits>; case_insensitive_string a{"hello"}; case_insensitive_string b{"hElLo"}; assert(a == b);
Barry source share