C strcmp() Function: Compare Strings

In C language, the strcmp() function can be used to compare the sizes of two strings. This function compares the characters in the strings based on their ASCII values, stopping when it finds a difference or one string ends.

The syntax of the strcmp() function is as follows:

int strcmp(const char *str1, const char *str2);

Among them, str1 and str2 are the two strings to be compared. If str1 is less than str2, return a negative number; if str1 is equal to str2, return 0; if str1 is greater than str2, return a positive number.

For example:

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

int main() {
    char str1[] = "apple";
    char str2[] = "banana";
    
    int result = strcmp(str1, str2);
    
    if (result < 0) {
        printf("str1 is less than str2");
    } else if (result == 0) {
        printf("str1 is equal to str2");
    } else {
        printf("str1 is greater than str2");
    }
    
    return 0;
}

In the example above, where str1 is “apple” and str2 is “banana”, after comparing them using the strcmp() function, the result shows that str1 is less than str2. Therefore, the output is “str1 is less than str2”.

bannerAds