Strings: Comparing

Dave Sinkula 0 Tallied Votes 1K Views Share

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

See also Strings: Comparing, Case-Insensitive.

#include <stdio.h>

int mystrcmp(const char *dst, const char *src)
{
   for ( ; *dst && *src; ++src, ++dst )
   {
      if ( *dst != *src )
      {
         break;
      }
   }
   return *dst - *src;
}

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("mystrcmp(\"%s\", \"%s\") = %d\n", text[i], text[j], 
                mystrcmp(text[i], text[j]));
      }
   }
   return 0;
}

/* my output
mystrcmp("hello", "world") = -15
mystrcmp("hello", "hello") = 0
mystrcmp("hello", "hell") = 111
mystrcmp("world", "hello") = 15
mystrcmp("world", "hell") = 15
mystrcmp("hello", "hell") = 111
*/
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.