C 庫 - strcoll() 函式



C 庫函式 `strcoll()` 接收兩個指標變數,用於比較兩個字串(例如 str1 和 str2)。結果取決於位置的 LC_COLLATE 設定。

它的功能是根據區域設定的方式比較字串。字串比較函式(例如 strcmp)執行簡單的逐位元組比較,而 strcoll() 會考慮當前區域設定。這允許根據重要的規則(例如字母順序和大小寫敏感性)進行字串比較。

語法

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

strcoll(const char *str1, const char *str2)

引數

此函式接受以下引數:

  • str1 − 這是要比較的第一個字串。

  • str2 − 這是要比較的第二個字串。

返回值

此函式返回整數值:

  • 如果 < 0,則 str1 小於 str2。
  • 如果 > 0,則 str2 小於 str1。
  • 如果 = 0,則 str1 等於 str2。

示例 1

以下 C 庫程式演示了 `strcoll()` 函式。

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

int main () {
   char str1[15];
   char str2[15];
   int ret;

   strcpy(str1, "abc");
   strcpy(str2, "ABC");

   ret = strcoll(str1, str2);

   if(ret > 0) {
      printf("str1 is less than str2");
   } 
   else if(ret < 0) {
      printf("str2 is less than str1");
   } 
   else {
      printf("str1 is equal to str2");
   }
   return(0);
}

輸出

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

str1 is less than str2

示例 2

在這裡,我們三次使用 strcoll() 來確定正、負和零的整數值結果。

#include <stdio.h> 
#include <string.h>
 
int main()
{
   char str1[50] = "abcdef"; 
   char str2[50] = "abcdefgh"; 
   char str3[] =  "ghijk";  
   char str4[] =  "GHIJK";  
   int x, y, z;
	
   x = strcoll(str1, str2);		
   printf("\n The Comparison of str1 and str2 Strings = %d", x);
 	
   y = strcoll(str3, str4);		
   printf("\n The Comparison of str3 and str4 Strings = %d", y);
   
   z = strcoll(str1, "abcdef");		
   printf("\n The Comparison of both Strings = %d", z);

return 0;
}

輸出

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

 The Comparison of str1 and str2 Strings = -103
 The Comparison of str3 and str4 Strings = 32
 The Comparison of both Strings = 0

示例 3

我們不列印整數值,而是列印簡單的訊息,顯示比較語句。

#include <stdio.h> 
#include <string.h>
 
int main()
{
   char string1[50] = "abcdefgh";
   char string2[50] = "ABCDEFGH";
   int res
	
   res = strcoll(string1, string2);
   
   if(res < 0) {
   		printf("\n string1 is Less than string2");
	}
   else if(result > 0) {
   		printf("\n string2 is Less than string1");
	}
	else {
   		printf("\n string1 is Equal to string2");
	}
	return 0;
}

輸出

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

string2 is Less than string1
廣告