How to compare characters in strings one by one in the C language?

In C language, you can compare each character of two strings using the strcmp() function. The prototype of the strcmp() function is in the string.h header file, and its usage is as follows:

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

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

    int result = strcmp(str1, str2);

    if (result == 0) {
        printf("两个字符串相等\n");
    } else if (result < 0) {
        printf("%s 在 %s 之前\n", str1, str2);
    } else {
        printf("%s 在 %s 之后\n", str1, str2);
    }

    return 0;
}

In the example above, the strcmp() function compares each character of str1 and str2. If the two strings are equal, strcmp() returns 0; if the first string comes before the second string in the dictionary, strcmp() returns a negative value; if the first string comes after the second string in the dictionary, strcmp() returns a positive value.

Please note that the strcmp() function is case-sensitive. If you want to do a case-insensitive comparison, you can use the strcasecmp() function.

bannerAds