C language: detailed explanation of strncmp() usage

1. Introduction to strncmp()

1. Function prototype

int strncmp(const char *str1, const char *str2, size_t n);

2. Parameters

  • str1 -The first string to be compared.
  • str2 -The second string to be compared.
  • n -the maximum number of characters to compare.

3. Function

Used to compare the first n characters of the string str1 and str2.

4. Header files

#include <string.h>

5. Return value

  • From left to right , compare n characters one by one according to the ASCII code value, until a different character appears or encounter'\0', the value of str1-str2 is the return value.
  • If the return value is <0, it means str1 is less than str2.
  • If the return value> 0, it means that str2 is less than str1.
  • If the return value = 0, it means that str1 is equal to str2.

Two, strncmp() usage

The strncmp function is used to compare strings.
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("strncmp(a, b):%d\n", strncmp(a, b, 7));//字符串之间的比较 
    printf("strncmp(a, c):%d\n", strncmp(a, c, 7));
    printf("strncmp(a, d):%d\n", strncmp(a, d, 7));
    printf("strncmp(a, \"English\"):%d\n", strncmp(a, "English", 7));
    printf("strncmp(&a[2], \"g\"):%d\n", strncmp(&a[2], "g", 1)); //单个字符的比较
	return 0;
}

The results are as follows:

strncmp(a, b):32
strncmp(a, c):-32
strncmp(a, d):0
strncmp(a, "English"):0
strncmp(&a[2], "g"):0

Guess you like

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