The strcmp()
method is used to compare two strings in the C programming language. It accepts two string parameters and returns negative values if the first string is lower than the second string. Return 0 if both strings are the same. Returns a positive value if the second string is lower than the first string.
strcmp() Method Syntax
The strcmp() method has the following syntax. The return type of the strcmp() is integer which is set according to the result.
int strcmp(const char *STR1, const char *STR2)
- STR1 is the first string we want to compare.
- STR2 is the second string we want to compare.
Compare Two Strings
In the following example, we compare two strings ” apple” and “pine”. We put the result to the variable named result
which is an integer.
#include <stdio.h>
#include <string.h>
int main ()
{
char str1[] = "apple";
char str2[] = "pine";
int result = strcmp(str1,str2);
printf("%d",result);
return 0;
}
Alternatively, we can provide one string parameter as values to the strcmp() method like below.
#include <stdio.h>
#include <string.h>
int main ()
{
char str2[] = "pine";
int result = strcmp("apple",str2);
printf("%d",result);
return 0;
}
Compare Interactive Input
We can also get some interactive input via the standard input or command-line interface. The scanf()
method can be used to read input like below.
#include <stdio.h>
#include <string.h>
int main ()
{
char str1[] = "apple";
char str2[30] ;
scanf("%s",str2);
int result = strcmp(str1,str2);
printf("%d",result);
return 0;
}