c语言strcmp函数

来源:百度知道 编辑:UC知道 时间:2024/05/29 23:13:34
#include <stdio.h>
#include <string.h>

int main(void)
{
const char *s1 = "happy new year";
const char *s2 = "happy new year";
const char *s3 = "happy holidays";

printf("%s%s\n%s%s\n%s%s\n\n%s%2d\n%s%2d\n%s%2d\n\n",
"s1 = ", s1, "s2 = ", s2, "s3 = ", s3,
"strcmp(s1, s2) = ", strcmp(s1, s2),
"strcmp(s1, s3) = ", strcmp(s1, s3),
"strcmp(s3, s1) = ", strcmp(s3, s1)
);
return 0;
}
上面其中的
"strcmp(s1, s3) = ", strcmp(s1, s3),
"strcmp(s3, s1) = ", strcmp(s3, s1)
为什么返回的是
6
-6呢?s3的“h”不是大于s1的“n”么?另外为什么不是返回的1,而是返回的是6?和OS相关?上面是在solaris中运行的结果,谢谢!

strcmp返回的实际上是两个字符串中第一个不同的字符的ASCII码的差,差大于0说明是>关系,小于0则是<关系.6>0,和1一样是表示大于,而且返回ASCII码的确切差值,可以方便用来实现一些其他的应用,比只知道大于带来了更多的信息

返回值是第一个不相等的字符的ascii值的差

'h'的ascii值为104
'n'的为110

所以'n'比'h'大

第一个返回的是'n'-'h'=6
第二次是-6
不懂hi我