Compare if two strings are equal in the C language.
In C language, you can utilize the strcmp function to compare if two strings are equal.
The prototype of the strcmp function is:
int strcmp(const char *str1, const char *str2);
The parameters str1 and str2 are the two strings to be compared.
If two strings are equal, the strcmp function will return 0; if str1 is less than str2, it will return a negative value; if str1 is greater than str2, it will return a positive value.
Here is an example code demonstrating how to compare if two strings are equal:
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "Hello";
char str2[] = "Hello";
char str3[] = "World";
if (strcmp(str1, str2) == 0) {
printf("str1和str2相等\n");
} else {
printf("str1和str2不相等\n");
}
if (strcmp(str1, str3) == 0) {
printf("str1和str3相等\n");
} else {
printf("str1和str3不相等\n");
}
return 0;
}
Result of execution:
str1和str2相等
str1和str3不相等