How to use the C language string comparison function?
In C language, the strcmp function is used to compare strings. The prototype of the strcmp function is as follows:
int strcmp(const char *str1, const char *str2);
This function takes two parameters, which are the two strings to be compared, str1 and str2. It returns 0 if the two strings are equal, a value greater than 0 if str1 is greater than str2, and a value less than 0 if str1 is less than str2.
Here is an example code using the strcmp function to compare strings:
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "Hello";
char str2[] = "World";
int result = strcmp(str1, str2);
if (result == 0) {
printf("两个字符串相等\n");
} else if (result > 0) {
printf("str1大于str2\n");
} else {
printf("str1小于str2\n");
}
return 0;
}
The output result is:
str1小于str2
This indicates that str1 is smaller than str2.