Case-Insensitive C-String Comparison
How can I implement a case-insensitive string comparison using C-style strings?
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:
- We use a while loop to iterate through both strings simultaneously.
- For each character, we use
std::tolower()
to convert to lowercase before comparing. - If we find a difference, we return it immediately.
- If we reach the end of one or both strings, we compare the last characters (which might be null terminators).
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.
Working with C-Style Strings
A guide to working with and manipulating C-style strings, using the
library