How to compare strings in the C programming language

In C language, comparing strings requires using the strcmp function, which compares the ASCII values of two strings. For example, the following code demonstrates how to compare two strings:

#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("str1小于str2\n");
    }
    else {
        printf("str1大于str2\n");
    }
    
    return 0;
}

The output result is:

str1小于str2

If you want to compare without considering case sensitivity, you can use the stricmp function instead of the strcmp function.

bannerAds