[サンプルコード付き]C言語 文字列比較関数 strcmp

strcmp

strcmp

書式

#include <string.h>
int strcmp(const char *s1, const char *s2);

引数

const char *s1 : 比較文字列1
const char *s2 : 比較文字列2

戻り値

文字コードの大小関係で戻りが変わる。
s1 > s2 で正の値
s1 < s2 で負の値
s1 = s2で 0 を返却する

サンプルコード

#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[])
{
    const char s1[] = { "abc" };
    const char s2[] = { "abb" };
    const char s3[] = { "abd" };
    int        ret;
    
    /* 文字列が等しいパターン */
    ret = strcmp(s1, s1);
    printf("%d = strcmp(%s, %s)\n", ret, s1, s1);

    /* 第一引数の方が大きいパターン */
    ret = strcmp(s1, s2);
    printf("%d = strcmp(%s, %s)\n", ret, s1, s2);

    /* 第二引数の方が大きいパターン */
    ret = strcmp(s1, s3);
    printf("%d = strcmp(%s, %s)\n", ret, s1, s3);
    return 0;
}

実行結果

0 = strcmp(abc, abc)
1 = strcmp(abc, abb)
-1 = strcmp(abc, abd)

注意する点

strcmp関数は文字列の終端をNULL文字で判定しているため、
NULL文字が含まれない文字だと再現なく比較してしまうため注意が必要です。

コメント

タイトルとURLをコピーしました