「C言語でstrcmpを使用して文字列のサイズを比較する方法は?」
strcmp関数は、2つの文字列を比較して大小を判定し、3つの結果を返します。
- s1とs2が等しい場合は、0を返す。
- s1がs2よりも大きい場合、正の数を返す。
- s1がs2より小さい場合、負の数を返す。
strcmp関数を使用して文字列の大小を比較する例です。
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "abc";
char str2[] = "def";
int result = strcmp(str1, str2);
if (result == 0) {
printf("str1 is equal to str2\n");
} else if (result > 0) {
printf("str1 is greater than str2\n");
} else {
printf("str1 is less than str2\n");
}
return 0;
}
結果は以下の通りです:
str1 is less than str2
この例では、文字列”abc”は文字列”def”よりも小さいので、strcmpは負の値を返します。