The strxfrm function transforms (into a new collated form) the string pointed to by s2 and places the resulting string into the array pointed to by s1.
The transformation is made using the locale’s LC_COLLATE category setting and No more than n characters, including the null character, are transformed and placed into the resulting array pointed to by s1.
The strxfrm function transforms the string in such a way that if we call to strcmp with the two transformed strings, the result same as a call to strcoll applied to the original two strings.
Syntax of strxfrm function:
size_t strxfrm(char * restrict s1, const char * restrict s2, size_t n);
parameters:
s1: This is the string that receives n characters of the transformed string.
s2: This is the string that is to be transformed.
n: This is the maximum number of characters which to be copied into str1.
Return:
The strxfrm function returns the length of the transformed string, not including the terminating null character (‘\0’). If the return value is greater than or equal to n, the content of s1 is unpredictable.
Some important points related to strxfrm in C:
1.) In the “C” locale, the order of the characters in the character set (ASCII character set) is the same as the lexicographic order of the characters. So In the “C” locale only, strxfrm is equivalent to strncpy. Let’s see the example code.
#include <stdio.h> #include <string.h> #include <locale.h> int main() { char src[] = "Aticleworld"; char dst[20]; size_t len; //Set locale "C" setlocale( LC_ALL, "C" ); printf( "%s\n", src ); len = strxfrm( dst, src, 20 ); printf( "%s (%u)\n", dst, len ); return 0; }
Output:
Aticleworld
Aticleworld (11)
2.) If n is 0, then destination array s1 is allowed to be a null pointer.
3.) The below expression evaluates the correct size of the array needed to hold the transformation of the string pointed to by s.
//Expression to get array size 1 + strxfrm(NULL, s, 0);
4.) In locales for which the character set and the lexicographic character order differ, use strxfrm on the original strings and then strcmp on the resulting strings to produce a lexicographic string comparison according to the current locale’s LC_COLLATE category setting. Alternately, you can use strcoll rather than strcmp on the original strings.
#include <stdio.h> #include <string.h> #include <locale.h> int main() { setlocale(LC_COLLATE, "cs_CZ.iso88592"); const char* s1 = "hrnec"; const char* s2 = "chrt"; char t1[1+strxfrm(NULL, s1, 0)]; char t2[1+strxfrm(NULL, s2, 0)]; //compare original string with strcoll printf("%d\n", strcoll(s1,s2)); //compare original string printf("%d\n",strcmp(s1,s2)); strxfrm(t1,s1,sizeof(t1)); strxfrm(t2,s2,sizeof(t2)); //compare transfered string printf("%d\n", strcmp(t1,t2)); return 0; }
Output: Using GCC9.2 (C17)
5
1
5