C语言 strcmp() 在 C 中返回值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7656475/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 09:49:04  来源:igfitidea点击:

strcmp() return values in C

cstrcmp

提问by dmubu

I am learning about strcmp()in C. I understand that when two strings are equal, strcmpreturns 0.

我正在学习strcmp()C。我知道当两个字符串相等时,strcmp返回 0。

However, when the man pages state that strcmpreturns less than 0 when the first string is less than the second string, is it referring to length, ASCII values, or something else?

但是,当手册页声明strcmp第一个字符串小于第二个字符串时返回小于 0 时,它是指长度、ASCII 值还是其他内容?

回答by Mysticial

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

从这个意义上说,字符串的“小于”表示字典(字母)顺序。

So catis less than dogbecause catis alphabetically before dog.

Socat小于dog因为cat按字母顺序排列在 之前dog

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

从某种意义上说,词典顺序是所有 ASCII(和 UNICODE)字符的字母顺序的扩展。

回答by JRL

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.

大于零的值表示不匹配的第一个字符在第一个字符串中的值大于第二个字符串中的值,小于零的值表示相反。

回答by Keith Thompson

C997.21.4:

C997.21.4:

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

比较函数memcmpstrcmpstrncmp返回的非零值的符号由被比较对象中 不同的第一对字符(均被解释为unsigned char)的值之间的差的符号决定。

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().

请特别注意,结果不依赖于当前的语言环境;LC_COLLATE(参见 C99 7.11)影响strcoll()strxfrm(),但不影响strcmp()

回答by Rani

    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;
    }

回答by Dalbir Singh

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

看看下面的程序,这里我根据你输入的字符串返回值。该函数strcmp根据整个字符串的 ASCII 值重新计算值。

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

例如。str1 = "aab"并且str2 = "aaa"将返回1为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;
}