Jun 26, 2016

C Programming #77: strcmp implementation

C Programming #77: strcmp implementation

Following article implements our own version of strcmp implementation. Please review article strings and string.h library if not already done. Since our implementation function name would clash with standard implementation, lets prefix my_ to it. We know the prototype of my_strcmp is as follow.

/*Compare the strings s1 with s2.*/
int my_strcmp(const char *s1, const char *s2);

Return type of strcmp will tell how the implementation has to be done. If you see the man pages it tells the return value could be

The strcmp() and strncmp() functions return an 
integer  less  than,  equal  to,  or greater 
than zero if s1 (or the first n bytes thereof) 
is found, respectively, to be less than, to match, 
or be greater than s2.

In simple terms it returns

  1. 0 - if the string match.
  2. difference(of course ASCII) in first non matching character between s1 and s2.

Now as part of algo we need to keep on comparing s1, s2 till

  1. s1 is '\0'
  2. s2 is '\0'
  3. and characters in s1 and s2 are same.
#include <stdio.h>
#include <string.h>
int my_strcmp(char *s1, char*s2);
int main()
{
   char a[50] = "hello world";
   char b[50] = "hello world";
   char c[50] = "india";
   int d;

   if(0 == (d = my_strcmp(a, b))) {
       printf("string %s and %s are same\n", a, b);
   }else {
       printf("string %s and %s are not same\n", a, b);
   }
   printf("d after strcmp is %d\n", d);

   if(0 == (d = my_strcmp(a, c))) {
       printf("string %s and %s are same\n", a, c);
   }else {
       printf("string %s and %s are not same\n", a, c);
   }
   printf("d after strcmp is %d\n", d);

   if(0 == (d = my_strcmp(c, a))) {
       printf("string %s and %s are same\n", a, c);
   }else {
       printf("string %s and %s are not same\n", a, c);
   }
   printf("d after strcmp is %d\n", d);

   return 0;
}
int my_strcmp(char *s1, char*s2)
{
   while(*s1 != '\0' && *s2 != '\0' && *s1 == *s2) {
      s1++;
      s2++;
   }
   return (*s1 - *s2);
}
string hello world and hello world are same
d after strcmp is 0
string hello world and india are not same
d after strcmp is -1
string hello world and india are not same
d after strcmp is 1

Never use custom implementation like this, always use the standard implementation provided in glibc.

No comments :

Post a Comment