Implementing a case-insensitive string comparison for C-style strings requires a custom function, as the standard strcmp()
is case-sensitive. We'll create a function that compares strings character by character, converting each to lowercase before comparison.
Here's an implementation:
#include <cctype>
#include <cstring>
#include <iostream>
int strcasecmp(const char* s1, const char* s2) {
while (*s1 && *s2) {
int diff{
std::tolower(*s1) - std::tolower(*s2)
};
if (diff != 0) {
return diff;
}
s1++;
s2++;
}
return std::tolower(*s1) - std::tolower(*s2);
}
int main() {
const char* str1{"Hello"};
const char* str2{"hElLo"};
const char* str3{"World"};
std::cout << "Comparing "
<< str1 << " and " << str2
<< ": " << strcasecmp(str1, str2) << '\n';
std::cout << "Comparing "
<< str1 << " and " << str3
<< ": " << strcasecmp(str1, str3) << '\n';
}
Comparing Hello and hElLo: 0
Comparing Hello and World: -15
Let's break down the strcasecmp()
 function:
std::tolower()
to convert to lowercase before comparing.This function returns 0 for equal strings, a negative value if s1 is lexicographically before s2 (ignoring case), and a positive value otherwise.
Note that this implementation is not optimal for large strings or frequent comparisons, as it converts each character to lowercase on every comparison. For better performance in such scenarios, you might want to consider creating lowercase copies of the strings first, or using a lookup table for case conversion.
Also, be aware that this simple implementation doesn't handle locale-specific case conversions. For more complex scenarios involving different languages or Unicode, you'd need to use more sophisticated libraries or techniques.
Answers to questions are automatically generated and may not have been reviewed.
A guide to working with and manipulating C-style strings, using the
library