strxfrm() Function

The strxfrm() function transforms a given string according to locale-specific collation rules. It converts the string into a form suitable for locale-aware comparison, allowing binary comparison to yield results consistent with the locale’s rules.


Syntax of strxfrm()

</>
Copy
size_t strxfrm(char *destination, const char *source, size_t num);

Parameters

ParameterDescription
destinationPointer to the destination array for the transformed string. It may be a null pointer if num is zero.
sourceC string to be transformed.
numMaximum number of characters to be copied to the destination array.

Return Value

The function returns the length of the transformed string, not including the terminating null-character.

Notes

The behavior of strxfrm() depends on the current locale’s collation settings (LC_COLLATE). It is useful for preparing strings for locale-aware comparisons, such as when sorting. Additionally, if you only need the length of the transformed string without actually copying it, you can pass a null pointer for the destination and 0 for the number of characters.


Examples for strxfrm()

Example 1: Transforming a String for Locale-Aware Comparison

This example demonstrates how to transform a string according to the current locale settings and display both the transformed string and its length.

Program

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

int main() {
    // Set locale for collation rules
    setlocale(LC_COLLATE, "");

    char source[] = "apple";
    char transformed[50];

    // Transform the string according to the current locale
    size_t len = strxfrm(transformed, source, sizeof(transformed));

    printf("Transformed string: %s\n", transformed);
    printf("Length of transformed string: %zu\n", len);
    return 0;
}

Output:

Transformed string: apple
Length of transformed string: 5

Example 2: Retrieving Only the Length of the Transformed String

This example shows how to obtain the length of the transformed string without copying the transformed data.

Program

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

int main() {
    // Set locale for proper collation transformation
    setlocale(LC_COLLATE, "");

    char source[] = "banana";

    // Retrieve the length of the transformed string without copying it
    size_t len = strxfrm(NULL, source, 0);

    printf("Length of transformed string: %zu\n", len);
    return 0;
}

Output:

Length of transformed string: 6