我有2个字符串要比较,我认为使用strncmp
会比使用更好,strcmp
因为我知道其中一个字符串的长度。
char * a = "hel";
char * b = "he"; // in my real code this is scanned so it user dependent
for(size_t i = 0; i < 5; i++){
printf("strncmp: %d\n", strncmp(a,b,i));
}
我期望输出是
0
0
0
1 // which is the output of printf("strcmp: %d\n", strncmp(a,b));
1
因为只有在第四次迭代(i = 3
)中字符串才开始不同,但是我得到了
0
0
0
108 // guessing this is due to 'l' == 108 in ascii
108
我不明白为什么,正如男人所说:
该
strcmp()
函数比较两个字符串s1和s2。如果分别找到s1小于,匹配或大于s2,则它返回小于,等于或大于零的整数。该
strncmp()
功能与之类似,只不过它仅比较s1和s2的前(最多)n个字节。
这意味着它应该在到达a之后停止,'\0'
并因此仅返回1(如strcmp
),不是吗?
从您发布的报价中:
...返回小于,等于或大于零的整数...
这两个1
和108
是整数大于0的有没有保障功能必须返回1
或-1
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句