名前空間
変種
操作

std::strncmp

提供: cppreference.com
< cpp‎ | string‎ | byte
ヘッダ <cstring> で定義
int strncmp( const char *lhs, const char *rhs, std::size_t count );

ヌル終端されているかもしれない2つの配列を最大 count 文字まで比較します。 比較は辞書的に行われます。 ヌル文字の後の文字は比較されません。

結果の符号は比較する配列内の最初の異なる文字の組の値 (どちらも unsigned char として解釈されます) の差の符号です。

配列 lhs または rhs いずれかの終端を超えてアクセスが発生した場合、動作は未定義です。 lhs または rhs のいずれかがヌルポインタの場合、動作は未定義です。

目次

[編集] 引数

lhs, rhs - 比較するヌル終端されているかもしれない配列を指すポインタ
count - 比較する最大文字数

[編集] 戻り値

辞書順で lhsrhs より前に現れる場合は負の値。

lhsrhs が等しい場合または count がゼロの場合はゼロ。

辞書順で lhsrhs より後に現れる場合は正の値。

[編集] ノート

std::strcollstd::strxfrm と異なり、この関数はロケール対応ではありません。

[編集]

#include <cstring>
#include <iostream>
 
void demo(const char* lhs, const char* rhs, int sz)
{
    int rc = std::strncmp(lhs, rhs, sz);
    if(rc == 0)
        std::cout << "First " << sz << " chars of ["
                  << lhs << "] equal [" << rhs << "]\n";
    else if(rc < 0)
        std::cout << "First " << sz << " chars of ["
                  << lhs << "] precede [" << rhs << "]\n";
    else if(rc > 0)
        std::cout << "First " << sz << " chars of ["
                  << lhs << "] follow [" << rhs << "]\n";
}
int main()
{
    demo("Hello, world!", "Hello, everybody!", 13);
    demo("Hello, everybody!", "Hello, world!", 13);
    demo("Hello, everybody!", "Hello, world!", 7);
    demo("Hello, everybody!" + 12, "Hello, somebody!" + 11, 5);
}

出力:

First 13 chars of [Hello, world!] follow [Hello, everybody!]
First 13 chars of [Hello, everybody!] precede [Hello, world!]
First 7 chars of [Hello, everybody!] equal [Hello, world!]
First 5 chars of [body!] equal [body!]

[編集] 関連項目

2つの文字列を比較します
(関数) [edit]
2つのワイド文字列の文字を一定量比較します
(関数) [edit]
2つのバッファを比較します
(関数) [edit]
現在のロケールに従って2つの文字列を比較します
(関数) [edit]