strncmp
提供: cppreference.com
<tbody>
</tbody>
| ヘッダ <string.h> で定義
|
||
int strncmp( const char *lhs, const char *rhs, size_t count ); |
||
ヌル終端されているかもしれない2つの配列を最大 count 文字まで比較します。 比較は辞書的に行われます。
結果の符号は比較する文字列内の最初の異なる文字の組の値 (どちらも unsigned char として解釈されます) の差の符号です。 ヌル文字の後の文字は比較されません。
配列 lhs または rhs いずれかの終端を超えてアクセスが発生した場合、動作は未定義です。 lhs または rhs がヌルポインタの場合、動作は未定義です。
引数
| lhs, rhs | - | 比較するヌル終端されているかもしれない配列を指すポインタ |
| count | - | 比較する最大文字数 |
戻り値
辞書順で lhs が rhs より前に現れる場合は負の値。
lhs と rhs が等しい場合または count がゼロの場合はゼロ。
辞書順で lhs が rhs より後に現れる場合は正の値。
ノート
strcoll や strxfrm と異なり、この関数はロケール対応ではありません。
例
Run this code
#include <string.h>
#include <stdio.h>
void demo(const char* lhs, const char* rhs, int sz)
{
int rc = strncmp(lhs, rhs, sz);
if(rc == 0)
printf("First %d chars of [%s] equal [%s]\n", sz, lhs, rhs);
else 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);
}
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!]
参考文献
- C11 standard (ISO/IEC 9899:2011):
- 7.24.4.4 The strncmp function (p: 366)