strncmp
|
定义于头文件
<string.h>
|
||
|
int
strncmp
(
const
char
*
lhs,
const
char
*
rhs,
size_t
count
)
;
|
||
比较两个可能以空字符结尾的数组,最多比较 count 个字符。该比较按字典序进行。空字符之后的字符不会被比较。
结果的符号取决于数组中第一对不相同字符(均被解释为 unsigned char )值的差值符号。
当访问超出数组 lhs 或 rhs 的末端时,其行为是未定义的。当 lhs 或 rhs 为空指针时,其行为也是未定义的。
目录 |
参数
| lhs, rhs | - | 指向可能以空字符结尾的数组的指针,用于比较 |
| count | - | 要比较的最大字符数 |
返回值
若 lhs 在字典序中出现在 rhs 之前,则返回负值。
当 lhs 与 rhs 比较相等,或 count 为零时返回零。
正值表示 lhs 在字典序中出现在 rhs 之后。
注释
此函数与 strcoll 和 strxfrm 不同,不涉及区域设置相关处理。
示例
#include <stdio.h> #include <string.h> void demo(const char* lhs, const char* rhs, int sz) { const int rc = strncmp(lhs, rhs, sz); if (rc < 0) printf("First %d chars of [%s] precede [%s]\n", sz, lhs, rhs); else if (rc > 0) printf("First %d chars of [%s] follow [%s]\n", sz, lhs, rhs); else printf("First %d chars of [%s] equal [%s]\n", sz, lhs, rhs); } int main(void) { const char* 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 strncmp 函数 (p: TBD)
- C17 标准 (ISO/IEC 9899:2018):
-
- 7.24.4.4 strncmp 函数 (p: 待定)
- C11 标准 (ISO/IEC 9899:2011):
-
- 7.24.4.4 strncmp 函数 (p: 366)
- C99标准(ISO/IEC 9899:1999):
-
- 7.21.4.4 strncmp函数(页:329)
- C89/C90 标准 (ISO/IEC 9899:1990):
-
- 4.11.4.4 strncmp 函数
参见
|
比较两个字符串
(函数) |
|
|
(C95)
|
比较两个宽字符串的指定数量字符
(函数) |
|
比较两个缓冲区
(函数) |
|
|
根据当前区域设置比较两个字符串
(函数) |
|
|
C++ documentation
for
strncmp
|
|