strcmp ()- 比較字串
格式
#include <string.h>
int strcmp(const char *string1, const char *string2);
語言層次
ANSI
安全執行緒
是
說明
strcmp()
函數會比較 string1 與 string2。 函數對空值結束字串進行操作。 函數的字串引數應該包含標示字串結尾的空值字元 (\0)。
回覆值
strcmp()
函數會傳回一個值,指出兩個字串之間的關係,如下所示:
Value | 意義 |
---|---|
小於 0 | string1 小於 string2 |
0 | string1 與 string2相同 |
大於 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?"
**********************************************************************/