Comparing strings in the C language to determine if they are equal.
In C language, you can use the strcmp function to compare if two strings are equal. The prototype of the strcmp function is as follows:
int strcmp(const char *str1, const char *str2);
The function takes two parameters, which are the two strings to be compared. If the two strings are equal, the return value is 0; if str1 is less than str2, the return value is less than 0; if str1 is greater than str2, the return value is greater than 0. Here is an example code:
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "Hello";
char str2[] = "Hello";
char str3[] = "Hi";
if (strcmp(str1, str2) == 0) {
printf("str1 and str2 are equal.\n");
} else {
printf("str1 and str2 are not equal.\n");
}
if (strcmp(str1, str3) == 0) {
printf("str1 and str3 are equal.\n");
} else {
printf("str1 and str3 are not equal.\n");
}
return 0;
}
When running the code above, the output will be as follows:
str1 and str2 are equal.
str1 and str3 are not equal.