strcmp():
- It is Pre-defined function in string.h header file.
- Check the input strings are having same content or not.
- IF equal, returns 0.
- If not equal, returns non zero.
#include<stdio.h>
#include<string.h>
int main()
{
char s1[20] = "Hello";
char s2[20] = "Hello";
if(strcmp(s1,s2)==0)
printf("Strings are equal \n");
else
printf("String are not equal \n");
}
- strcmp() function consider the case.
- Lower case characters and Upper case characters treats differently.
#include<stdio.h>
#include<string.h>
int main()
{
char s1[20] = "hello";
char s2[20] = "Hello";
if(strcmp(s1,s2)==0)
printf("Strings are equal \n");
else
printf("String are not equal \n");
}
stricmp() function will not consider the case:
#include<stdio.h>
#include<string.h>
int main()
{
char s1[20] = "HELLO";
char s2[20] = "Hello";
if(stricmp(s1,s2)==0)
printf("Strings are equal \n");
else
printf("String are not equal \n");
}
strncmp() function checks only n characters are equal or not from the beginning of the string.
#include<stdio.h>
#include<string.h>
int main()
{
char s1[20] = "Hello all";
char s2[20] = "Hello everyone";
if(strncmp(s1,s2,5)==0)
printf("Strings having identical start \n");
else
printf("Strings not having identical start\n");
}
Note: strncmp() function is case-sensitive
C program to compare two strings without using string functions
- strcmp() function compares two string character by character until there is a mismatch occurs or end of the one of those strings reached whichever occurs first.
- If the two strings are equal, it returns 0. If two strings are not equal, it returns the numerical ASCII difference between the two mismatching characters.
#include<stdio.h>
int stringCompare(char[],char[]);
int main()
{
char str1[100],str2[100];
int compare;
printf("Enter first string: ");
gets(str1);
printf("Enter second string: ");
gets(str2);
compare = stringCompare(str1,str2);
if(compare == 1)
printf("Both strings are equal.\n");
else
{
printf("Both strings are not equal\n");
printf("the ascii difference between mismatching characters is :%d",compare);
}
return 0;
}
int stringCompare(char str1[],char str2[])
{
int i=0,flag=0;
while(str1[i]!='\0' && str2[i]!='\0')
{
if(str1[i]!=str2[i])
{
flag=1;
break;
}
i++;
}
if (flag==0 && str1[i]=='\0' && str2[i]=='\0')
return 1;
else
return str1[i]-str2[i];
}