C 庫 - strcmp() 函式



C 庫的 strcmp() 函式用於比較兩個字串。它逐個字元檢查字串,直到找到差異或到達其中一個字串的末尾。此外,字串比較基於 ASCII 值。

語法

以下是 C 庫 strcmp() 函式的語法:

strcmp(const char *str_1, const char *str_2)

引數

此函式接受以下引數:

  • str_1 − 此引數定義要比較的第一個字串。

  • str_2 − 這是與第一個/前一個字串進行比較的第二個字串。

返回值

此函式返回一個整數,其值為:

  • 零,如果字串相等。

  • 負數,如果第一個字串按字典順序小於第二個字串。

  • 正數,如果第一個字串按字典順序大於第二個字串。

示例 1

在此示例中,我們演示了使用 strcmp() 函式進行字串字元比較。

#include <stdio.h>
#include <string.h>

int main() {

   char str1[] = "abcd", str2[] = "abcd";
   int res;

   // Compare the strings str1 and str2
   res = strcmp(str1, str2);
   printf("strcmp(str1, str2) = %d\n", res);
   return 0;
}

輸出

以上程式碼產生以下結果:

strcmp(str1, str3) = 0

示例 2

使用 strcmp() 和條件語句檢查給定的字串是否區分大小寫。

#include <stdio.h>
#include <string.h>

int main() 
{
   char str1[] = "Tutorials";
   char str2[] = "tutorials";
   // Compare the strings
   int result = strcmp(str1, str2);
   
   if (result == 0) {
       printf("Strings are equal(case-sensitive)\n");
   } 
   else {
        printf("Strings are not equal(case-insensitive).\n");   
   }
return 0;
}

輸出

執行以上程式碼後,我們得到以下結果:

Strings are not equal(case-insensitive).

示例 3

以下示例建立不同大小的字串,並使用 strcmp() 檢查其比較結果。

#include <stdio.h>
#include <string.h>

int main() 
{
   char str_1[] = "BOOK";
   char str_2[] = "UNIVERSITY";

   int res = strcmp(str_1, str_2);

   if (res == 0) {
       printf("The strings are equal.\n");
   } 
   else if (res < 0) {
       printf("Str_1 is less than str_2.\n");
   } 
   else {
       printf("Str_1 is greater than str_2.\n");
   }
   return 0;
}

輸出

執行以上程式碼後,我們得到以下結果:

Str_1 is less than str_2.

示例 4

在這裡,我們使用 strcmp() 來比較兩個不同的字串,並藉助字典序。

#include <stdio.h>
#include <string.h>

int main { 

   char str1[] = "text";
   char str2[] = "notebook";

   int result = strcmp(str1, str2);
   if (result < 0) {
       printf("'%s' comes before '%s' lexicographically.\n", str1, str2);
   } 
   else if (result > 0) {
       printf("'%s' comes after '%s' lexicographically.\n", str1, str2);
   } 
   else {
      printf("Strings are equal.\n");
   }
    return 0;
}

解釋

在此程式碼中,str1 ("text") 按字典順序在 str2 ("Notebook") 之前。strcmp() 函式返回一個負值。

以上程式碼產生以下結果:

'text' comes after 'notebook' lexicographically.
廣告