How to compare strings in C language?
In C language, you can use the strcmp() function to compare two strings.
The strcmp() function takes two parameters, which are the two strings to be compared. It returns an integer value indicating the comparison result of the two strings. The specific comparison rules are as follows:
- If the two strings are equal, the return value is 0.
- Return a positive integer if the first string is greater than the second string.
- If the first string is less than the second string, return a negative integer.
Here is an example:
#include <stdio.h>
#include <string.h>
int main() {
char str1[20] = "Hello";
char str2[20] = "World";
int result;
result = strcmp(str1, str2);
if(result == 0) {
printf("两个字符串相等\n");
}
else if(result < 0) {
printf("第一个字符串小于第二个字符串\n");
}
else {
printf("第一个字符串大于第二个字符串\n");
}
return 0;
}
The output result is:
第一个字符串小于第二个字符串