C言語で文字列の大小を比較する方法

C言語では、`strcmp` 関数を使って2つの文字列の大きさを比較します。`strcmp` 関数のプロトタイプは次のとおりです。

int strcmp(const char* str1, const char* str2);

この関数は 2 つの文字列を引数にとり、str1 が str2 より小さければ負の整数、str1 が str2 と等しければ 0、str1 が str2 より大きければ正の整数という値を返します。

サンプルコードを以下に示します。

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

int main() {
    char str1[20] = "hello";
    char str2[20] = "world";

    int result = strcmp(str1, str2);

    if (result < 0) {
        printf("str1 is less than str2\n");
    } else if (result > 0) {
        printf("str1 is greater than str2\n");
    } else {
        printf("str1 is equal to str2\n");
    }

    return 0;
}

上記のコードは「str1 は str2 より小さい」を出力します。これは辞書順序で「hello」が「world」より小さいからです。

bannerAds