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
广告
© . All rights reserved.