User defined function of strcmp()

User defined function of strcmp()

strlen is used to compare two strings. If return value is zero means both strings are identical.

Prototype of strcmp() function : size_t strcmp( const char * str1, const char * str2);

Program of strcmp()

#include<stdio.h>

int own_strcmp(const char * str1, const char * str2)

{

  while(*str1 == *str2)

  {

    if(*str1 == ‘\0’)

      return 0;

    str1++;

    str2++;

  }

  return (*str1 – *str2);

}

int main()

{

  char str1[25];

  char str2[25];

   int value = 0;

         printf(“Enter first string to compare : “);

  gets(str1);

         printf(“Enter second string to compare : “);

  gets(str2);

        /* Own string compare function call */

   value = own_strcmp(str1,str2);

  printf(“Comparison of first and second string is  = %d\n”,value);

 if (0 == value)

        {

                printf(“Both strings are identical\n”);

        }

        else

{

                printf(“Both strings are  not identical\n”);

}

}

Output:

./a.exe

Enter first string to compare : gyan

Enter second string to compare : gyan

Comparison of first and second string is = 0

Both strings are identical

 

$ ./a.exe

Enter first string to compare : gyan

Enter second string to compare : gyantoday

Comparison of first and second string is = -116

Both strings are  not identical

One comment

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.