C言語のstrcmp関数の使い方は何ですか?
strcmp関数は、C言語における文字列比較関数であり、二つの文字列の大小を比較するために使用されます。
その機能のプロトタイプは:
int strcmp(const char *str1, const char *str2);
str1とstr2というパラメーターは、比較する2つの文字列です。 関数の戻り値は整数型で、いくつかの場合があります。
- もしstr1がstr2と等しい場合、0を返します。
- もしstr1がstr2より小さい場合、負の数を返す。
- str1がstr2よりも大きい場合、正の数を返す。
strcmp関数は、対応する文字を含む2つの文字列を辞書順で比較し、異なる文字が出るか、または2つの文字列の終わりに達するまで続けます。比較では、文字のASCII値を順番に比較します。
例えば、
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "hello";
char str2[] = "world";
int result = strcmp(str1, str2);
if (result == 0) {
printf("str1 equals to str2\n");
} else if (result < 0) {
printf("str1 is less than str2\n");
} else {
printf("str1 is greater than str2\n");
}
return 0;
}
出力結果は:
str1 is less than str2
上記の例では、”hello”と”world”という2つの文字列が比較され、”hello”が”world”よりも辞書順で小さいため、負の数が返されました。