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

The strcmp function is used to compare the sizes of two strings and has three possible return values.

  1. If s1 is equal to s2, return 0.
  2. If s1 is greater than s2, return a positive number.
  3. If s1 is less than s2, return a negative number.

Here is an example code of comparing string size using strcmp:

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

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

    int result = strcmp(str1, str2);

    if (result == 0) {
        printf("str1 is equal to str2\n");
    } else if (result > 0) {
        printf("str1 is greater than str2\n");
    } else {
        printf("str1 is less than str2\n");
    }

    return 0;
}

The output will be:

str1 is less than str2

In this example, the string “abc” is less than the string “def”, so strcmp returns a negative number.

bannerAds