Start New Discussion within our Software Development Community

How might I write an implementation in C of a case-insensitive version of the standard library function strcmp ? Here's how I might.

This this is often available as a nonstandard function that may be called stricmp , _stricmp , strcmpi , or strcasecmp .

See also Strings: Comparing.

#include <stdio.h>
#include <ctype.h>

int mystricmp(const char *a, const char *b)
{
   for ( ; *a && *b; ++a, ++b )
   {
      if ( toupper(*a) != toupper(*b) )
      {
         break;
      }
   }
   return toupper(*a) - toupper(*b);
}

int main (void)
{
   const char *text[] = { "hello", "world", "Hello", "hell"};
   size_t i, j;
   for ( i = 0; i < sizeof text / sizeof *text; ++i )
   {
      for ( j = i + 1; j < sizeof text / sizeof *text; ++j )
      {
         printf("mystricmp(\"%s\", \"%s\") = %d\n", text[i], text[j],
                mystricmp(text[i], text[j]));
      }
   }
   return 0;
}

/* my output
mystricmp("hello", "world") = -15
mystricmp("hello", "Hello") = 0
mystricmp("hello", "hell") = 79
mystricmp("world", "Hello") = 15
mystricmp("world", "hell") = 15
mystricmp("Hello", "hell") = 79
*/
The article starter has earned a lot of community kudos, and such articles offer a bounty for quality replies.