C String Function : strcmp()

The strcmp() function is used to compares two strings and returns 0 if both are strings are equal. The syntax for strcmp() is :
int strcmp ( const char * str1, const char * str2 );
Example :
value = strcmp(str1, str2);
  • If str1 and str2 is equal then, it returns 0.
  • If the length of str1 is greater then str2 ( str1 > str2 ), it returns greater then 0.
  • If the length of str1 is less then str2 ( str1 < str2 ), it returns less then 0.
Example of C program :
#include <stdio.h>
#include <string.h>

int main() {
  char str1[] = "This is Test String.";
  char str2[] = "This is Test String.";

  if(strcmp(str1, str2)==0) {
    printf("str1 and str2 are equal.\n");
  } else {
    printf("str1 and str2 are not equal.\n");
  }

  return 0;
}
Output :

str1 and str2 are equal.

Now lets see another example :
#include <stdio.h>
#include <string.h>

int main() {
  char str1[] = "Hello world";
  char str2[] = "This is Test String.";

  int val = strcmp(str1, str2);

  if(val == 0) {
    printf("str1 and str2 are equal.\n");
  } else if(val > 0) {     
    printf("Length of str1 is greater then str2.\n");
  } else if(val < 0) {
    printf("Length of str1 is less then str2.\n");
  }

  return 0;
}
Output :

Length of str1 is less then str2.

Note : We have to include the string.h header in our program to use the string function.

Links :