strncmp
来自 cppreference.cn
定义于头文件 <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: TBD)
- C11 标准 (ISO/IEC 9899:2011)
- 7.24.4.4 strncmp 函数 (p: 366)
- C99 标准 (ISO/IEC 9899:1999)
- 7.21.4.4 strncmp 函数 (p: 329)
- C89/C90 标准 (ISO/IEC 9899:1990)
- 4.11.4.4 strncmp 函数
[编辑] 参见
比较两个字符串 (函数) | |
(C95) |
从两个宽字符串比较一定数量的字符 (函数) |
比较两个缓冲区 (函数) | |
根据当前区域设置比较两个字符串 (函数) | |
C++ 文档 for strncmp
|