strcmp() — ストリングの比較

形式

#include <string.h>
int strcmp(const char *string1, const char *string2);

言語レベル

ANSI

スレッド・セーフ

はい

説明

strcmp() 関数は、 string1string2を比較します。 この関数は、ヌル終了ストリング上で作動します。 関数のストリング引数には、 ストリングの終わりを示すマークであるヌル文字 (\0) が含まれていなければなりません。

戻り値

strcmp() 関数は、以下のように、2 つのストリング間の関係を示す値を戻します。

表 1. strcmp() の戻り値
意味
0 より小さい値 string1string2 より小さい
0 string1string2 と等しい
0 より大きい string1string2 より大きい

この例では、 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?"
**********************************************************************/

関連情報