strcmp ()- 比较字符串

格式

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

语言级别

ANSI

线程安全

描述

strcmp() 函数将 string1string2进行比较。 该函数对以 null 结束的字符串进行操作。 函数的字符串自变量应包含标记字符串结束的空字符 (\0)。

返回值

strcmp() 函数返回一个值,指示两个字符串之间的关系,如下所示:

表 1. strcmp() 的返回值
含义
小于 0 string1 小于 string2
0 string1string2 相同
大于 0 string1 大于 string2

示例

此示例比较使用 strcmp()传递到 main() 的两个字符串。
#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?"
**********************************************************************/

相关信息