一、详解
二、区别
1. strcmp()与strncmp()的区别
strcmp与strncmp都是用来比较字符串的,区别在于能否比较指定长度字符串。
返回值不同:
- strcmp()返回的是-1和1。
- strncmp()返回的是str1-str2的数值。
具体代码如下:
#include <stdio.h>
#include <string.h>
int main(void)
{
char *a = "English";
char *b = "ENGLISH";
char *c = "english";
char *d = "English";
printf("strcmp(a, b):%d\n", strcmp(a, b));
printf("strncmp(a, b):%d\n", strncmp(a, b, 7));
printf("strcmp(a, c):%d\n", strcmp(a, c));
printf("strncmp(a, c):%d\n", strncmp(a, c, 7));
printf("strcmp(a, d):%d\n", strcmp(a, d));
printf("strncmp(a, d):%d\n", strncmp(a, d, 7));
return 0;
}
运行结果如下:
strcmp(a, b):1
strncmp(a, b):32
strcmp(a, c):-1
strncmp(a, c):-32
strcmp(a, d):0
strncmp(a, d):0
2. strncmp()与memcmp()的区别
strncmp比较的字符串,而memcmp比较的是内存块,strncmp需要时刻检查是否遇到了字符串结束的 /0 字符,而memcmp则完全不用担心这个问题,所以memcmp的效率要高于strncmp。
具体代码如下:
#include <stdio.h>
#include <string.h>
int main(void)
{
char a[10] = {'E','n','g','l','i','s','h',0,'A'};
char b[10] = {'E','n','g','l','i','s','h',0,'B'};
printf("strncmp(a, b):%d\n", strncmp(a, b, 10));
printf("memcmp(a, b):%d\n", memcmp(a, b, 10));
return 0;
}
运行结果如下:
strncmp(a, b):0
memcmp(a, b):-1