strncmp

来自cppreference.com
< c‎ | string‎ | byte
在标头 <string.h> 定义
int strncmp(constchar*lhs, constchar*rhs, size_t count );

比较两个可能空终止的数组的至多 count 个字符。按字典序进行比较。不比较后随空字符的字符。

结果的符号是被比较的数组中首对字符(都转译成 unsignedchar)的值间的差的符号。

若出现越过 lhsrhs 结尾的访问,则行为未定义。若 lhsrhs 为空指针,则行为未定义。

目录

[编辑]参数

lhs, rhs - 指向要比较的可能空终止的数组的指针
count - 要比较的最大字符数

[编辑]返回值

若字典序中 lhs 先于 rhs 出现则为负值。

lhsrhs 比较相等,或若 count 为零,则为零。

若字典序中 lhs 后于 rhs 出现则为正值。

[编辑]注解

不同于 strcollstrxfrm,此函数不考虑本地环境。

[编辑]示例

#include <stdio.h>#include <string.h>   void demo(constchar* lhs, constchar* rhs, int sz){constint rc = strncmp(lhs, rhs, sz);if(rc <0)printf("First %d chars of [%s] precede [%s]\n", sz, lhs, rhs);elseif(rc >0)printf("First %d chars of [%s] follow [%s]\n", sz, lhs, rhs);elseprintf("First %d chars of [%s] equal [%s]\n", sz, lhs, rhs);}int main(void){constchar* string ="Hello World!"; demo(string, "Hello!", 5); demo(string, "Hello", 10); demo(string, "Hello there", 10); demo("Hello, everybody!"+12, "Hello, somebody!"+11, 5);}

输出:

First 5 chars of [Hello World!] equal [Hello!] First 10 chars of [Hello World!] follow [Hello] First 10 chars of [Hello World!] precede [Hello there] First 5 chars of [body!] equal [body!]

[编辑]引用

  • C23 标准(ISO/IEC 9899:2024):
  • 7.24.4.4 The strncmp function (第 TBD 页)
  • C17 标准(ISO/IEC 9899:2018):
  • 7.24.4.4 The strncmp function (第 TBD 页)
  • C11 标准(ISO/IEC 9899:2011):
  • 7.24.4.4 The strncmp function (第 366 页)
  • C99 标准(ISO/IEC 9899:1999):
  • 7.21.4.4 The strncmp function (第 329 页)
  • C89/C90 标准(ISO/IEC 9899:1990):
  • 4.11.4.4 The strncmp function

[编辑]参阅

比较两个字符串
(函数)[编辑]
(C95)
比较来自两个宽字符串的一定量字符
(函数)[编辑]
比较两块缓冲区
(函数)[编辑]
比较两个字符串,根据当前本地环境
(函数)[编辑]
strncmp 的 C++ 文档
close