strcmp in c

strcmp() function in c

Declaration:

int strcmp(const char *str1, const char *str2);

This function strcmp is used for comparision of two strings, if the two string match then it return value 0, other wise it returns non zero value. it compares the string character by characters and the comparision stops when this end of the string is reached.

strcmp(str1,str2) return a value-
<0 when str1 < str2
=0 when str1==str2
>0 when str1>str2

Note: we should know only that if str1 < str2 then negative value will be return and if str1 > str2 then positiVe value will be return let us take example with the program

/* Program to understand use of strcmp() */
#include<stdio.h>
#include<string.h>
int
main()
{
char str1[15],str2[15];
printf("Enter first string :");
gets(str1);
printf("Enter second string :");
gets(str2);
if(strcmp(str1,str2)==0)
{
printf("Both string is equal");
}
else
{
printf("Both string are not equal");
}
return 0;
}

output:
Enter first string : delhi
Enter second string : belly
Both string are not equal

Lets us know how we can create like this function


int astrcmp(char str1[], char str2[])
{
int i;
for(i=0;str1[i]!=null;i++)
{
if(str[i]==’\0′)
{
return 0;
}
}
return(str1[i]-str2[i]);
}