strcmp() Function


The strcmp() method compares two strings identified by the arguments and has a value of 0 if they are equal. If they do not exist, it contains numerical differences between the first non-matching characters in the string. It takes the form :

strcmp(str1,str2);

str1 and str2 may be string variables or string constants. Examples are :

strcmp(str1,str2);
strcmp(str1,"hello");
strcmp("hello","world");

Our major concern is to determine whether the strings are equal; if not, which is alphabetically above. The value of the mismatch is rarely important. For example, the statement

strcmp("their","there");

will return a value of -9 which is the numeric difference between ASCII "i" and ASCII "r". That is, "i" minus "r" in ASCII code is -9. If the value is negative, str1 is alphabetically above str2.


Sample Program

Program
#include <stdio.h>
#include <string.h>

int main() {
  char str1[50] = "VERY";
  char str2[20] = "VERY";
  char str3[20] = "BAD ";
  
  if(!strcmp(str1,str2))
   printf("Two strings are equal.");
  else
   printf("Two strings are not equal.");
  return 0;
}