strcoll() in C - Source Code Example

In this source code example, we will see how to use the strcoll() function in C programming with an example.

Function Overview

The strcoll() function in C is used to compare two strings in a locale-sensitive manner. It compares the two strings based on the current locale's collation rules, which are used to determine the order of characters. This function is particularly useful when performing string comparisons that need to take language-specific sorting rules into account. 

Key Points: 

- The strcoll() function compares strings based on the locale's collation rules. 

- It returns an integer value representing the comparison result: 

  •  Negative value if the first string is less than the second string 
  •  Positive value if the first string is greater than the second string 
  •  Zero if the strings are equal 

- This function is locale-sensitive, meaning that the comparison outcome can differ based on the locale set for the program. 

- The comparison may involve not only the characters' values but also their ordering according to the locale's rules.

Source Code Example

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

int main() {
    // Set the locale to the system's default
    setlocale(LC_COLLATE, "");

    // Sample strings for comparison
    char str1[] = "apple";
    char str2[] = "banana";

    // Compare the strings using strcoll()
    int comparison = strcoll(str1, str2);

    if (comparison < 0) {
        printf("'%s' is less than '%s'\n", str1, str2);
    } else if (comparison > 0) {
        printf("'%s' is greater than '%s'\n", str1, str2);
    } else {
        printf("'%s' is equal to '%s'\n", str1, str2);
    }

    return 0;
}

Output

'apple' is less than 'banana'

Explanation

1. We begin by including the necessary headers: <stdio.h>, <string.h>, and <locale.h>.

2. The main() function sets the program's locale to the system's default using setlocale() with LC_COLLATE as the category. This ensures that string comparisons are performed according to the locale's collation rules.

3. Sample strings str1 and str2 are defined for comparison.

4. The strcoll() function is used to compare the two strings based on the current locale's collation rules. The result is stored in the comparison variable.

5. Conditional statements are used to determine whether str1 is less than, greater than, or equal to str2 based on the comparison result.

6. In this example, the output indicates that 'apple' is less than 'banana' according to the locale's collation rules.


Comments