They say that premature optimization is the root of all evil, and they are right. Most likely, this code performs as well as, or potentially even worse than, checking that strcmp(s1, s2) == 0.
Nonetheless, while working on my Google Summer of Code project, I needed to test that two strings are equal while ignoring the case. As a result I wrote a simple algorithm called strieq(s1,s2) which simply returns 1 if the strings are equal, and 0 otherwise. This differs from strcmp because strcmp provides the stuff necessary for an actual lexicographical comparison, which my particular application didn’t require.
So here I publish my code for your viewing pleasure. Possibly you will be able to use it, and while I’ve tested it and tried to make it safe, I’m not an extremely experienced C coder, so I may have missed something. If there is a bug, please report it (via e-mail or in the comments section) so that I can update it.
int strieq(const char *, const char *); static inline char lower(char); /* strieq(const char *str1, const char *str2) * * This function takes two ASCII strings and compares them for equality in a * case-insensitive manner. It doesn't work with Unicode strings -- that is, * it will only fix case for normal ASCII strings. Everything else is passed * through as-is. */ int strieq(const char *str1, const char *str2) { while (TRUE) { if ((*str1 == '' && *str2 != '') || (*str1 != '' && *str2 == '')) break; /* From the above test we know that they are either both non-null or both * strings are at the end. The latter case means we have a match. */ else if (*str1 == '') return TRUE; /* Check if the lowercased version of the characters match */ if (lower(*str1) != lower(*str2)) break; str1++; str2++; } return FALSE; } /* lower(char ch) * * This function takes a single alphabetic ASCII character and makes it * lowercase, useful for comparison. */ static inline char lower(char ch) { /* Check that ch is between A and Z */ if (ch >= 'A' && ch <= 'Z') return (ch + ('a' - 'A')); /* Otherwise return it as-is */ return ch; }
In case this is an issue:
I, the copyright holder of the above snippet for stricmp and lower, hereby release the entire contents therein into the public domain. This applies worldwide, to the extent that it is permissible by law.
In case this is not legally possible, I grant any entity the right to use this work for any purpose, without any conditions, unless such conditions are required by law.
Update: Small fixes to documentation and code; WordPress must have stripped characters when I first inserted the code.