Tuesday, April 20, 2010

Comparing strings without regard to case

I couldn't find a C++/STL built-in comparison function for strings without regard to case. I really thought there would be one, but apparently not.

So here's one for example.


// Compare two strings without regard to alphabetic case
int stricmp(const char *a, const char *b) {

static const int offset = 'a' - 'A';
for (; *a && *b; a++,b++) {
if (*a != *b) {
char la = 'A' <= *a && *a <= 'Z' ? *a+offset : *a;
char lb = 'A' <= *b && *b <= 'Z' ? *b+offset : *b;
int diff = la - lb;
if (diff) { return diff; }
}
}

return *a ? 1 : *b ? -1 : 0;

}

// Compare two pointers-to-strings without regard to alphabetic case
int sorting_stricmp( const void *a, const void *b ) {
const char **s1 = (const char **)a;
const char **s2 = (const char **)b;
return stricmp(*s1,*s2);
}

// Compare two C++ strings without regard to alphabetic case
int string_icmp(const string &s1, const string &s2) {
return stricmp(s1.c_str(), s2.c_str());
}

No comments:

Post a Comment

Followers