C言語 strcmp関数:文字列比較の基本と実践

strcmp関数は、2つの文字列の大きさを比較するための関数であり、そのプロトタイプは次の通りです:

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

その中で、str1とstr2は比較される2つの文字列です。

strcmp関数の戻り値には3つのケースがあります。

  1. もしstr1とstr2が等しい場合は、0を返します。
  2. str1がstr2より大きい場合、正の数を返す。
  3. str1がstr2よりも小さい場合、負の数を返す。

strcmp関数を使用したサンプルコードが以下に示されています。

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

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

    int result = strcmp(str1, str2);

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

    return 0;
}

このサンプルコードでは、”hello”と”world”という2つの文字列を比較し、比較結果に応じて情報を出力しています。

bannerAds