Strings: Comparing, Case-Insensitive

Dave Sinkula 0 Tallied Votes 343 Views Share

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
*/
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.