C言語では、2つのchar型の文字列が等しいかどうかを判定する方法は何ですか。

C言語では、strcmp関数を使用して、2つのchar型文字列が等しいかどうかを判断できます。

strcmp関数のプロトタイプは、int strcmp(const char *str1、const char *str2)です。

その関数は、str1とstr2の2つの文字列を比較し、整数値を返します。2つの文字列が等しい場合、0を返します。str1がstr2よりも小さい場合は、負の数を返し、str1がstr2よりも大きい場合は正の数を返します。

以下は、strcmp関数を使用して2つのchar文字列が等しいかどうかを判断する方法を示したサンプルコードです。

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

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

    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