The ones who are crazy enough to think they can change the world are the ones who do.- Steve Jobs
strcmp() is one of the inbuilt string function in c programming which is used to compare two strings, if the strings are same then the function returns 0. Otherwise it returns a nonzero value.
The following diagram clearly illustrate the working principle of strcmp() inbuilt string function in C.
strcmp(str1, str2);
Let us work through strcmp() function. In the following program we will compare two strings using strcmp() inbuilt string function.
#include <stdio.h>
#include<string.h>
int main()
{
char str1[20] = "this is strcmp", str2[20] = "this is strcmp";
if(strcmp(str1, str2) == 0)
printf("The strings str1 and str2 are same ");
return 0;
}
The strings str1 and str2 are same
The above program defines the function strcmp(), which is used to compare two strings. Here, str1 and str2 are same, so it returns 0 and prints the statement inside the condition.
Let us compare two strings without using inbuilt string function strcmp().
#include <stdio.h>
#include<string.h>
int main()
{
char str1[20] = "this is strcmp";
char str2[20] = "this is strcmp";
int i, j = 0;
for(i=0; str1[i]!='\0'; i++){
if(str1[i] == str2[i]) {
j++;
}
else {
j++;
printf("The strings str1 and str2 are not equal");
break;
}
}
if(i==j)
printf("The strings str1 and str2 are equal");
return 0;
}
The strings str1 and str2 are same
The above program looks verbose but yields the same result.
| Type | Return Value |
|---|---|
| str1 > str2. | 1 |
| str1 == str2. | 0 |
| str1 < str2. | -1 |
We may make mistakes(spelling, program bug, typing mistake and etc.), So we have this container to collect mistakes. We highly respect your findings.
© Copyright 2019