函式
<cstring>

strcmp

int strcmp ( const char * str1, const char * str2 );
比較兩個字串
比較 C 字串 str1 和 C 字串 str2

此函式從每個字串的第一個字元開始比較。如果它們彼此相等,則繼續比較後續的字元對,直到字元不同或到達終止的空字元為止。

此函式對字元執行二進位制比較。有關考慮特定於區域設定規則的函式,請參閱 strcoll

引數

str1
要比較的 C 字串。
str2
要比較的 C 字串。

返回值

返回一個整數值,指示兩個字串之間的關係
返回值表示
<0第一個不匹配的字元在 ptr1 中的值小於在 ptr2 中的值
0兩個字串的內容相等
>0第一個不匹配的字元在 ptr1 中的值大於在 ptr2 中的值

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <stdio.h>
#include <string.h>

int main ()
{
  char key[] = "apple";
  char buffer[80];
  do {
     printf ("Guess my favorite fruit? ");
     fflush (stdout);
     scanf ("%79s",buffer);
  } while (strcmp (key,buffer) != 0);
  puts ("Correct answer!");
  return 0;
}

輸出

Guess my favourite fruit? orange
Guess my favourite fruit? apple
Correct answer!


另見