strcmp(): String Comparison (String Handling Function)

In C programming, string handling function strcmp() is used to compare two strings. This function returns 0 if two strings are same otherwise it returns some integer value other than 0.

strcmp() Syntax


integer_variable = strcmp( string1, string2);

strcmp() Example


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

int main()
{
 char str1[40], str2[40];
 int d;

 printf("Enter first string:\n");
 gets(str1);
 printf("Enter second string:\n");
 gets(str2);
 d = strcmp(str1, str2);
 if(d==0)
 {
  printf("Given strings are same.");
 }
 else
 {
  printf("Given strings are different.");
 }
 
 return 0;
}

strcmp() Program Output


Run 1:
--------------
Enter first string:
Welcome to C↲
Enter second String:
Welcome to C↲
Given strings are same.

Run 2:
--------------
Enter first string:
Welcome↲
Enter second String:
Welcome to C↲
Given strings are different.