Compare two Strings in C

strcmp(s1, s2) compares two strings i.e., ‘s1’ and ‘s2’ and finds out whether they are the same or not. This function will compare the strings character by character until and unless there is a mismatch in the characters of both strings.

If no mismatch means both the strings are identical, then the function will return 0.

While making the comparison if any pair of characters of both strings doesn’t match then it will return the difference of ASCII values of the first non-matching pair of characters.

Program

#include<stdio.h>
#include<string.h>
int main()
{
          char s1[]="Different";
          char s2[]="Difference";
           int a,b;
           a= strcmp(s1,"Different");
           b= strcmp(s1,s2);
           printf("%d\n%d",a,b);
}

 

Output

Compare two Strings in C

Explanation

a= strcmp(s1,”Different”); ‘a’ returns the value ‘0’ because ‘s1’ is compared with “Different” and both are identical.

b= strcmp(s1, s2); ‘s1’ is “Different” and ‘s2’ is “Difference”. The first mismatching pair will be (t,c) and the difference of their ASCII value is 17 (116-99). Thus, ‘b’ returns 17.

Leave a comment

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