C language: the difference between strcmp, strncmp, memcmp

1. Detailed

Two, the difference

1. The difference between strcmp() and strncmp()

Both strcmp and strncmp are used to compare strings, the difference is whether they can compare strings of a specified length.
The return value is different :

  • strcmp() returns -1 and 1.
  • strncmp() returns the value of str1-str2.
    The specific code is as follows:
#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;
}

The results are as follows:

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. The difference between strncmp() and memcmp()

Strncmp compares strings, while memcmp compares memory blocks. Strncmp needs to check whether it encounters the /0 character at the end of the string. Memcmp does not have to worry about this problem at all, so the efficiency of memcmp is higher than strncmp.
The specific code is as follows:

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

The results are as follows:

strncmp(a, b):0
memcmp(a, b):-1

Guess you like

Origin blog.csdn.net/MQ0522/article/details/111247481