C strcmp() Guide: Compare Strings
The strcmp function is used to compare the size of two strings, and its prototype is:
int strcmp(const char *str1, const char *str2);
“其中,str1 and str2 are the two strings being compared.”
There are three possible return values for the strcmp function.
- Return 0 if str1 is equal to str2.
- If str1 is greater than str2, return a positive number.
- If str1 is less than str2, return a negative number.
Here is an example code using the strcmp function:
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "hello";
char str2[] = "world";
int result = strcmp(str1, str2);
if (result == 0) {
printf("str1 and str2 are equal\n");
} else if (result > 0) {
printf("str1 is greater than str2\n");
} else {
printf("str1 is less than str2\n");
}
return 0;
}
In this code snippet, we compared the sizes of two strings “hello” and “world” and printed the corresponding information based on the comparison result.