strxfrm() in C/C++

The strxfrm() function transforms a source string according to the current locale's collating sequence and copies the transformed string to a destination buffer. It is declared in <locale.h> header file and is useful for locale-sensitive string comparisons.

Syntax

size_t strxfrm(char *destination, const char *source, size_t number);

Parameters

  • destination − Pointer to the destination buffer where transformed characters will be copied
  • source − Pointer to the null-terminated source string to be transformed
  • number − Maximum number of characters to copy to destination

Return Value

Returns the length of the transformed string (excluding null terminator). If the return value is greater than or equal to number, the destination string is truncated.

Example

Here is a basic example demonstrating the use of strxfrm()

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

int main() {
    char source[] = "HelloWorld";
    char destination[20];
    int length;
    
    // Set locale to C (default)
    setlocale(LC_ALL, "C");
    
    // Transform and copy first 5 characters
    length = strxfrm(destination, source, 5);
    
    printf("Source string: %s\n", source);
    printf("Transformed string: %s\n", destination);
    printf("Total transformed length: %d\n", length);
    
    return 0;
}
Source string: HelloWorld
Transformed string: Hell
Total transformed length: 10

Key Points

  • The function returns the total length of the transformed string, not just the copied portion
  • If the return value is ? number, the destination buffer may be truncated
  • The transformation depends on the current locale's LC_COLLATE category
  • In the "C" locale, strxfrm() behaves similar to strncpy()

Conclusion

The strxfrm() function is essential for locale-aware string transformations and comparisons. It transforms strings according to the current locale's collating rules, making it useful for internationalization and proper string sorting in different languages.

Updated on: 2026-03-15T09:55:56+05:30

401 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements