对于两个字符串str1和str2,如何比较用strcmp()这两个之间的“大小”呢?是将两个字符串中每一个字符的ASCII码值累加之后再比较吗?

  strcmp()返回值有时候是0,1,-1,有时候又是2,有时候是两个字符之间的ASCII码值(两个字符串都只有一个字符,不包含‘\0’),它有具体意义吗?

  如果str1字符串字节比较小但每个字符ASCII码值比较大,str2字符串字节比较大但每个字符ASCII码值比较小,那在这种情况下strcmp()会怎么判定呢?

  感谢老师不吝赐教!

 (我用的是vscode,c11标准,WSL连接Ubuntu子系统,gcc9.3.0)

  

  

 

Comments  

+1 # Moderator 2021-12-09 19:26
大小顺序应该是字典序。想象一下英文字典的顺序。

字符大小关系应该按编码值大小计算。
+2 # Moderator 2021-12-09 19:24
最可靠的办法就是查看手册,在linux下,man strcmp:
DESCRIPTION
The strcmp() function compares the two strings s1
and s2. It returns an integer less than, equal
to, or greater than zero if s1 is found, respec‐
tively, to be less than, to match, or be greater
than s2.

The strncmp() function is similar, except it com‐
pares the only first (at most) n bytes of s1 and
s2.

这就说函数语义的全部描述。
具体值取决于不同编译器的实现,本身没有意义。也就是你不能拿来用。
+2 # yuanyuan 2021-12-10 23:56
NOTES
POSIX.1 specifies only that:

The sign of a nonzero return value shall be determined by the
sign of the difference between the values of the first pair of
bytes (both interpreted as type unsigned char) that differ in
the strings being compared.

In glibc, as in most other implementations, the return value is the
arithmetic result of subtracting the last compared byte in s2 from
the last compared byte in s1. (If the two characters are equal, this
difference is 0.)
按照posix标准,在*nix系统是比较第一位不同的字节

You have no rights to post comments