Write a program to implement your own strcmp() function

No replies
shashwat
Offline
Last seen: 1 year 8 weeks ago
Joined: 2009-02-18
bOt Points: 1160

The strcmp() function in C/C++ is used to compare two strings. It compares both the strings character by character from the starting until the characters differ or until a terminating null-character is reached. This function may return following values:

  • A zero value indicates that both strings are equal.
  • A value greater than zero indicates that the first character that does not match has a greater value in str1 than in str2
  • And a value less than zero indicates the opposite.

We will also implement our mystrcmp() function along the similar lines. Check out the code given below:

#include<stdio.h>

int mystrcmp(const char * str1, const char * str2)
{
  while(*str1 == *str2)
  {
    if(*str1 == '\0')
      return 0;
    str1++;
    str2++;
  }
  return (*str1 - *str2);
}

int main()
{
  char str1[] = "TEST";
  char str2[] = "TEST";
  char str3[] = "TAST";
  printf("Comparison of str1 and str2 = %d\n",mystrcmp(str1,str2));
  printf("Comparison of str1 and str3 = %d\n",mystrcmp(str1,str3));
}

Output:

Output for implementing your own strcmp() function

The above OUTPUT was generated by bOtskOOl Online Compiler - Try it out now>>

Founder and Admin