strcmp() return values in C [duplicate]

こ雲淡風輕ζ 提交于 2019-11-27 01:49:35

In this sense, "less than" for strings means lexicographic (alphabetical) order.

So cat is less than dog because cat is alphabetically before dog.

Lexicographic order is, in some sense, an extension of alphabetical order to all ASCII (and UNICODE) characters.

A value greater than zero indicates that the first character that does not match has a greater value in the first string than in the second, and a value less than zero indicates the opposite.

C99 7.21.4:

The sign of a nonzero value returned by the comparison functions memcmp, strcmp, and strncmp is determined by the sign of the difference between the values of the first pair of characters (both interpreted as unsigned char) that differ in the objects being compared.

Note in particular that the result doesn't depend on the current locale; LC_COLLATE (see C99 7.11) affects strcoll() and strxfrm(), but not strcmp().

    int strcmp (const char * s1, const char * s2)
    {
        for(; *s1 == *s2; ++s1, ++s2)
           if(*s1 == 0)
               return 0;
        return *(unsigned char *)s1 < *(unsigned char *)s2 ? -1 : 1;
    }
Dalbir Singh

Look out the following program, here I am returning the value depending upon the string you have typed. The function strcmp retrun value according to ASCII value of whole string considered totally.

For eg. str1 = "aab" and str2 = "aaa" will return 1 as aab > aaa.

int main()
{
    char str1[15], str2[15];
    int n;
    printf("Enter the str1 string: ");

    gets(str1);
    printf("Enter the str2 string : ");
    gets(str2);
    n = strcmp(str1, str2);
    printf("Value returned = %d\n", n);
    return 0;
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!