How to compare the size of strings in the C language?

In the C language, the strcmp function can be used to compare the sizes of two strings. This function has three possible return values.

  1. If the return value is less than 0, it means the first string is smaller than the second string.
  2. If the return value is 0, it means that the two strings are equal.
  3. If the return value is greater than 0, it means the first string is greater than the second string.

The code example is shown below:

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

int main() {
    char str1[100], str2[100];
    printf("输入第一个字符串: ");
    scanf("%s", str1);
    printf("输入第二个字符串: ");
    scanf("%s", str2);

    int result = strcmp(str1, str2);
    if (result < 0) {
        printf("%s 小于 %s\n", str1, str2);
    } else if (result == 0) {
        printf("%s 等于 %s\n", str1, str2);
    } else {
        printf("%s 大于 %s\n", str1, str2);
    }
    
    return 0;
}

In the above code, we used the strcmp function to compare two strings and printed different results based on the return value.

bannerAds