C言語で文字列を比較する方法は何ですか?

C言語では、文字列の比較はstrcmp関数を使って行うことができます。strcmp関数のプロトタイプは次の通りです:

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

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

以下は文字列のサイズを比較するサンプルコードです。

#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 is less than str2
bannerAds