C言語のstrcmp関数の使い方は何ですか?

strcmpはC言語における文字列比較関数であり、2つの文字列が等しいかどうかを比較します。

関数のプロトタイプは以下のとおりです:

int strcmp(const char *s1, const char *s2);

パラメータ s1 と s2 は、比較される 2 つの文字列です。

文字列s1とs2が等しい場合、つまり対応する位置の文字が全て等しい場合は、0 を返します。

文字列s1がs2より大きい場合、0より大きい値を返す。

s1がs2より小さい場合、負の値を返します。

下記に strcmp 関数の使用例を示します。

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

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

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

    return 0;
}

彼女はすぐに部屋を飛び出した

str1 is smaller than str2

「Hello」という文字列は「World」という文字列よりもアルファベット順に小さいからです。

bannerAds