C String Comparison: strcmp vs strcpy Guide

In the C language, the strcmp function is used to compare the sizes of two strings. The strcpy function is used to copy one string to another string, not to compare string sizes.

Here is an example code to compare the size of 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("str1 is less than str2\n");
    } else if(result > 0) {
        printf("str1 is greater than str2\n");
    } else {
        printf("str1 is equal to str2\n");
    }

    return 0;
}

In the above code, we use the strcmp function to compare the sizes of two strings, str1 and str2, and output the corresponding information based on the comparison result. The strcmp function returns an integer: if the return value is less than 0, it means the first string is less than the second string; if the return value is greater than 0, it means the first string is greater than the second string; if the return value is equal to 0, it means the two strings are equal.

bannerAds