C言語の文字列を比較して等しいかどうかを確認します。

C言語では、strcmp関数を使って2つの文字列が等しいかどうかを比較することができます。strcmp関数のプロトタイプは以下の通りです:

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

この関数は、比較する2つの文字列を受け取ります。2つの文字列が等しい場合、値は0を返します。str1がstr2より小さい場合、値は0未満を返します。str1がstr2より大きい場合、値は0より大きいを返します。以下はサンプルコードです:

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

int main() {
    char str1[] = "Hello";
    char str2[] = "Hello";
    char str3[] = "Hi";

    if (strcmp(str1, str2) == 0) {
        printf("str1 and str2 are equal.\n");
    } else {
        printf("str1 and str2 are not equal.\n");
    }

    if (strcmp(str1, str3) == 0) {
        printf("str1 and str3 are equal.\n");
    } else {
        printf("str1 and str3 are not equal.\n");
    }

    return 0;
}

上記のコードを実行し、結果は次の通りです:

str1 and str2 are equal.
str1 and str3 are not equal.
bannerAds