Case Insensitive String Comparison in C
There is no function that does this in the C standard. Unix systems that comply with POSIX are required to have strcasecmp
in the header strings.h
; Microsoft systems have stricmp
. To be on the portable side, write your own:
int strcicmp(char const *a, char const *b){ for (;; a++, b++) { int d = tolower((unsigned char)*a) - tolower((unsigned char)*b); if (d != 0 || !*a) return d; }}
But note that none of these solutions will work with UTF-8 strings, only ASCII ones.
I've found built-in such method named from which contains additional string functions to the standard header .
Here's the relevant signatures :
int strcasecmp(const char *, const char *);int strncasecmp(const char *, const char *, size_t);
I also found it's synonym in xnu kernel (osfmk/device/subrs.c) and it's implemented in the following code, so you wouldn't expect to have any change of behavior in number compared to the original strcmp function.
tolower(unsigned char ch) { if (ch >= 'A' && ch <= 'Z') ch = 'a' + (ch - 'A'); return ch; }int strcasecmp(const char *s1, const char *s2) { const unsigned char *us1 = (const u_char *)s1, *us2 = (const u_char *)s2; while (tolower(*us1) == tolower(*us2++)) if (*us1++ == '\0') return (0); return (tolower(*us1) - tolower(*--us2));}