How do you compare two strings in C language?
In the C language, you can compare two strings using the strcmp() function.
The prototype of the strcmp() function is as follows:
int strcmp(const char *str1, const char *str2);
The function takes two parameters, which are pointers to the two strings to be compared. It will compare the characters at corresponding positions based on their ASCII codes, until it finds a different character or one of the strings ends. A return value of 0 indicates that the two strings are equal, a negative return value indicates that str1 is less than str2, and a positive return value indicates that str1 is greater than str2.
Here is an example code that compares two strings.
Include the standard input/output and string libraries.
int main() {
char str1[20] = “Hello”;
char str2[20] = “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;
My friend asked me to go with him to the concert, but I had already made other plans.
The output shows that str1 is less than str2.