strcmp関数でC言語の文字列比較:大小判定の基本

C言語では、strcmp()関数を使って、2つの文字列を比較することができる。strcmp()関数は、ASCIIコード値を一つずつ比較し、異なる文字が見つかるか、どちらかの文字列が終了するまで比較を続ける。

strcmp()関数の構文は以下の通りです:

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

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

例えば、

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

int main() {
    char str1[] = "apple";
    char str2[] = "banana";
    
    int result = strcmp(str1, str2);
    
    if (result < 0) {
        printf("str1 is less than str2");
    } else if (result == 0) {
        printf("str1 is equal to str2");
    } else {
        printf("str1 is greater than str2");
    }
    
    return 0;
}

str1が”apple”であり、str2が”banana”である場合、strcmp()関数を使って比較すると、結果はstr1がstr2よりも小さいことになり、したがって出力は”str1 is less than str2″となります。

bannerAds