The
strcmp()
compares two strings character by character. If the strings are equal, the function returns 0.
The syntax of strcmp()
is:
strcmp (str1,str2);
Return Value from strcmp()
Return Value | Remarks | |||||||
---|---|---|---|---|---|---|---|---|
0 |
if strings are equal | |||||||
non-zero | if strings are not equal |
Example
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "mybcaclassnotes";
char str2[] = "myBCAclassnotes", str3[] = "mybcaclassnotes";
int result;
// comparing strings str1 and str2
result = strcmp(str1, str2);
printf("strcmp(str1, str2) = %d\n", result);
// comparing strings str1 and str3
result = strcmp(str1, str3);
printf("strcmp(str1, str3) = %d\n", result);
return 0;
}
Output
To Compare Two Strings without using strcmp()
#include<stdio.h>
int main() {
char str1[30], str2[30];
int i;
printf("\nEnter First strings :");
gets(str1);
printf("\nEnter Secfond strings :");
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);
}
Output
No comments:
Post a Comment