How can you compare two strings for equality in C language?

In C language, the strcmp() function can be used to compare if two strings are the same. The function will return an integer value: 0 if the two strings are equal, a negative number if the first string is less than the second, and a positive number if the first string is greater than the second.

Here is an example code comparing two strings for equality:

#include <stdio.h>
#include <string.h>

int main() {
    char str1[] = "Hello";
    char str2[] = "Hello";

    if (strcmp(str1, str2) == 0) {
        printf("两个字符串相等\n");
    } else {
        printf("两个字符串不相等\n");
    }

    return 0;
}

In the example above, we are using the strcmp() function to compare whether two strings, str1 and str2, are equal. If they are equal, it will print “The two strings are equal”, otherwise it will print “The two strings are not equal”.

bannerAds