/    /  Strcmp Function

Strcmp Function

 

This function compares two strings based on ASCII value.Strcmp() returns value as 0 if both are equal otherwise non zero.It compares character by character and comparison stops either at end of string is reached or corresponding character in the two strings are not equal.

 

strcmp(s1,s2) value is = 0 if s1==s2
                       > 0 if s1>s2
                       < 0 if s1< s2

 

Example Program:

 

C program to compare two strings using string handling functions.

 

#include<stdio.h>
#include<string.h>
main()
{
char s[10],s1[10];
int x;
printf("enter string 1 ");
gets(s);
printf("enter string 2 ");
gets(s1);
printf("strings are\n");
puts(s);
puts(s1);
x=strcmp(s,s1);
if(x==0)
printf("strings are equal");
else
if(x>0)
printf("string1 is greater than string2");
else
printf("string1 is lesser than string2");
}

 

Output1:

 

Strcmp Function

 

Output2:

 

Strcmp Function

 

Example Program:

 

C program to compare two strings without using string handling functions.

 

#include<stdio.h>
int main()
{
char str1[30], str2[30];
int i;
printf("\nEnter two strings :");
gets(str1);
gets(str2);
i = 0;
while (str1[i] == str2[i] && str1[i] != '\0')
i++;
if (str1[i] > str2[i])
printf("str1 > str2");
else if (str1[i] < str2[i])
printf("str1 < str2");
else
printf("str1 = str2");
return (0);
}

 

Output1:

 

Strcmp Function

 

Output2:

 

Strcmp Function