strncmp
来自cppreference.com
<tbody>
</tbody>
| 在标头 <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 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++ 文档
| |