strcmp() — ストリングの比較
フォーマット
#include <string.h>
int strcmp(const char *string1, const char *string2);
言語レベル
ANSI
スレッド・セーフ
はい
説明
strcmp() 関数は、string1 と string2 を比較します。 この関数は、ヌル終了ストリング上で作動します。 関数のストリング引数には、 ストリングの終わりを示すマークであるヌル文字 (\0) が含まれていなければなりません。
戻り値
strcmp() 関数は、2 つのストリング間の関係を示す次のような値を戻します。
| 値 | 意味 |
|---|---|
| 0 より小さい値 | string1 は string2 より小さい |
| 0 | string1 は string2 と等しい |
| 0 より大きい値 | string1 は string2 より大きい |
例
この例では、strcmp() を使用して main() に渡される 2 つのストリングを比較します。
#include <stdio.h>
#include <string.h>
int main(int argc, char ** argv)
{
int result;
if ( argc != 3 )
{
printf( "Usage: %s string1 string2¥n", argv[0] );
}
else
{
result = strcmp( argv[1], argv[2] );
if ( result == 0 )
printf( "¥"%s¥" is identical to ¥"%s¥"¥n", argv[1], argv[2] );
else if ( result < 0 )
printf( "¥"%s¥" is less than ¥"%s¥"¥n", argv[1], argv[2] );
else
printf( "¥"%s¥" is greater than ¥"%s¥"¥n", argv[1], argv[2] );
}
}
/****************** If the input is the strings ***********************
********** "is this first?" and "is this before that one?", ***********
****************** then the expected output is: *********************
"is this first?" is greater than "is this before that one?"
**********************************************************************/