C/C++ 中的 strcmp()


函式 strcmp() 是一個內建的庫函式,它在“string.h”標頭檔案中宣告。此函式用於比較字串引數。它按字典順序比較字串,這意味著它逐個字元地比較兩個字串。它從字串的第一個字元開始比較,直到兩個字串的字元相等或找到 NULL 字元。

如果兩個字串的第一個字元相等,則檢查第二個字元,依此類推。此過程將持續進行,直到找到 NULL 字元或兩個字元不相等。

以下是 C 語言中 strcmp() 的語法:

int strcmp(const char *leftStr, const char *rightStr );

此函式根據比較返回以下三個不同的值。

1.零 (0) - 如果兩個字串相同,則返回零。兩個字串中的所有字元都相同。

以下是 C 語言中兩個字串相等時 strcmp() 的示例:

示例

 現場演示

#include<stdio.h>
#include<string.h>
int main() {
   char str1[] = "Tom!";
   char str2[] = "Tom!";
   int result = strcmp(str1, str2);
   if (result==0)
   printf("Strings are equal");
   else
   printf("Strings are unequal");
   printf("\nValue returned by strcmp() is: %d" , result);
   return 0;
}

輸出

Strings are equal
Value returned by strcmp() is: 0

2.大於零 (>0) - 當左側字串的匹配字元的 ASCII 值大於右側字串的字元的 ASCII 值時,它返回一個大於零的值。

以下是 C 語言中 strcmp() 返回大於零值時的示例:

示例

 現場演示

#include<stdio.h>
#include<string.h>
int main() {
   char str1[] = "hello World!";
   char str2[] = "Hello World!";
   int result = strcmp(str1, str2);
   if (result==0)
   printf("Strings are equal");
   else
   printf("Strings are unequal");
   printf("\nValue returned by strcmp() is: %d" , result);
   return 0;
}

輸出

Strings are unequal
Value returned by strcmp() is: 32

3.小於零 (<0) - 當左側字串的匹配字元的 ASCII 值小於右側字串的字元的 ASCII 值時,它返回一個小於零的值。

以下是 C 語言中 strcmp() 的示例

示例

 現場演示

#include<stdio.h>
#include<string.h>
int main() {
   char leftStr[] = "Hello World!";
   char rightStr[] = "hello World!";
   int result = strcmp(leftStr, rightStr);
   if (result==0)
   printf("Strings are equal");
   else
   printf("Strings are unequal");
   printf("\nValue returned by strcmp() is: %d" , result);
   return 0;
}

輸出

Strings are unequal
Value returned by strcmp() is: -32

更新於: 2020-06-24

27K+ 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告