stricmp, comparing two strings in C case-insensitively

12 August 2009

For some reason, I found that the stricmp() function isn’t implemented in standard C. So I implemented mine, which works for ASCII strings only.

Maybe it’s not that all interesting, but I’ll post it here, if someone needs it:

#include <string.h>
#include <stdio.h>

int
stricmp (const char *s1, const char *s2)
{
   if (s1 == NULL) return s2 == NULL ? 0 : -(*s2);
   if (s2 == NULL) return *s1;

   char c1, c2;
   while ((c1 = tolower (*s1)) == (c2 = tolower (*s2)))
   {
     if (*s1 == '\0') break;
     ++s1; ++s2;
   }

   return c1 - c2;
}

int
main ()
{
   const char *a = NULL;
   const char *b = NULL;
   const char *c = "piPpO";
   const char *d = "pIpPa";
   const char *e = "";
   const char *f = "pippOdue";

   printf ("%d\t%d\t%d\t%d\t%d\t%d\t%d\n",
      stricmp (a, c),  // <0
      stricmp (c, a),  // >0
      stricmp (c, d),  // >0
      stricmp (c, c),  // =0
      stricmp (d, c),  // <0
      stricmp (e, e),  // =0
      stricmp (c, f)); // <0

   return 0;
}
Advertisements