CodingHowTo

Case-Insensitive String Compare in C++ the Simple Way

Case-Insensitive String Compare in C++ the Simple Way

Content

Using the C++ standard library, you can easily achieve case-insensitive comparison by converting both strings to either lower or upper case before comparing them. Here's a simple 10-liner guide:

```cpp
#include <iostream>
#include <algorithm>
#include <cctype>

bool iequals(const std::string& a, const std::string& b) {
    if (a.size() != b.size()) return false;
    for (size_t i = 0; i < a.size(); ++i)
        if (std::tolower(a[i]) != std::tolower(b[i])) return false;
    return true;
}

int main() {
    std::string str1 = "Hello";
    std::string str2 = "hello";

    if (iequals(str1, str2)) {
        std::cout << "Strings are equal (case-insensitive)" << std::endl;
    } else {
        std::cout << "Strings are not equal" << std::endl;
    }

    return 0;
}

Conclusion

Performing case-insensitive string comparisons in C++ can be efficiently handled by converting both strings to the same case (either lower or upper) before comparing them. This method leverages the standard library's `std::tolower` function, ensuring that the comparison is case-insensitive and straightforward.