strcoll() Function
The strcoll()
function in C performs a locale-aware comparison between two strings, examining each character in order based on the current collation rules. It determines the lexicographical order as defined by the LC_COLLATE setting of the active locale.
Syntax of strcoll()
int strcoll(const char *str1, const char *str2);
Parameters
Parameter | Description |
---|---|
str1 | C string to be compared. |
str2 | C string to be compared. |
The function compares the strings character by character according to locale-specific collation rules until a difference is found or the end of a string is reached. The result may vary based on the current LC_COLLATE setting, which governs the ordering of characters beyond standard ASCII values.
Return Value
The function returns an integer indicating the relationship between the two strings.
- A return value of 0 means the strings are equal.
- A value greater than 0 indicates that the first string is greater than the second.
- A value less than 0 indicates that it is less.
Examples for strcoll()
Example 1: Comparing Equal Strings
This example demonstrates how strcoll()
returns 0 when both strings are identical.
Program
#include
#include
int main() {
const char *s1 = "apple";
const char *s2 = "apple";
int result = strcoll(s1, s2);
printf("Comparison result: %d\n", result);
return 0;
}
Explanation:
- The two strings “apple” and “apple” are compared using
strcoll()
. - Since the strings are identical, the function returns 0.
- The result is printed to the console.
Output:
Comparison result: 0
Example 2: Comparing Different Strings
This example demonstrates how strcoll()
determines the lexicographical order. Here, the first string is expected to be less than the second string according to the current locale.
Program
#include
#include
int main() {
const char *s1 = "apple";
const char *s2 = "banana";
int result = strcoll(s1, s2);
printf("Comparison result: %d\n", result);
return 0;
}
Explanation:
- The strings “apple” and “banana” are compared using
strcoll()
. - Since “apple” comes before “banana” in the current locale’s collation order, the function returns a negative value.
- The result is printed to the console.
Output:
Comparison result: -1
Example 3: Comparing Strings with Reversed Order
This example shows how strcoll()
returns a positive value when the first string is lexicographically greater than the second string as determined by the current locale.
Program
#include
#include
int main() {
const char *s1 = "orange";
const char *s2 = "apple";
int result = strcoll(s1, s2);
printf("Comparison result: %d\n", result);
return 0;
}
Explanation:
- The strings “orange” and “apple” are compared using
strcoll()
. - Since “orange” is considered greater than “apple” in the current locale, the function returns a positive value.
- The result is printed to the console.
Output:
Comparison result: 1