How to compare strings in C programming language?
In C language, we can use the strcmp function to compare two 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. It compares the two strings in lexicographical order and returns an integer value that indicates the relationship between the two strings. A return value of 0 indicates that the two strings are equal, a value greater than 0 indicates that str1 is greater than str2, and a value less than 0 indicates that str1 is less than str2.
Example code:
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "Hello";
char str2[] = "World";
char str3[] = "Hello";
int result1 = strcmp(str1, str2);
int result2 = strcmp(str1, str3);
printf("str1 和 str2 比较结果: %d\n", result1);
printf("str1 和 str3 比较结果: %d\n", result2);
return 0;
}
Output result:
str1 和 str2 比较结果: -15
str1 和 str3 比较结果: 0
In the above examples, we compared str1 with str2 and str1 with str3, resulting in the corresponding comparison results.