@Go to the ‰ŠP�”›first@�”˜, ‰ŠP�”›previous@�”˜, ‰ŠP�”›next@�”˜, ‰ŠP�”›last@�”˜ section, ‰ŠP�”›table of contents@�”˜.
Œ

ˆ‰SEC57Št�”›String and Array Utilities

@�”˜Operations on strings (or arrays of characters) are an important part of many programs. The GNU C library provides an extensive set of string utility functions, including functions for copying, concatenating, comparing, and searching strings. Many of these functions can also operate on arbitrary regions of storage; for example, the Hmemcpy@ function can be used to copy the contents of any kind of array.
It's fairly common for beginning C programmers to "reinvent the wheel" by duplicating this functionality in their own code, but it pays to become familiar with the library functions and to make use of them, since this offers benefits in maintenance, efficiency, and portability.
For instance, you could easily compare one string to another in two lines of C code, but if you use the built-in Hstrcmp@ function, you're less likely to make a mistake. And, since these library functions are typically highly optimized, your program may run faster too.
ˆ‰SEC58Št�”›Representation of Strings

‰IDX343Š
@�”˜This section is a quick summary of string concepts for beginning C programmers. It describes how character strings are represented in C and some common pitfalls. If you are already familiar with this material, you can skip this section.
‰IDX344Š‰IDX345Š@�”˜A Bstring@ is an array of Hchar@ objects. But string-valued variables are usually declared to be pointers of type Hchar *@. Such variables do not include space for the text of a string; that has to be stored somewhere else--in an array variable, a string constant, or dynamically allocated memory (see section ‰ŠP�”›Memory Allocation@�”˜). It's up to you to store the address of the chosen memory space into the pointer variable. Alternatively you can store a Bnull pointer@ in the pointer variable. The null pointer does not point anywhere, so attempting to reference the string it points to gets an error.
By convention, a Bnull character@, H'\0'@, marks the end of a string. For example, in testing to see whether the Hchar *@ variable Bp@ points to a null character marking the end of a string, you can write H!*Jp@ or H*JpH == '\0'@.
A null character is quite different conceptually from a null pointer, although both are represented by the integer H0@.
‰IDX346ŠB�”˜String literals@ appear in C program source as strings of characters between double-quote characters (H`"'@). In ISO C, string literals can also be formed by Bstring concatenation@: H"a" "b"@ is the same as H"ab"@. Modification of string literals is not allowed by the GNU C compiler, because literals are placed in read-only storage.
Character arrays that are declared Hconst@ cannot be modified either. It's generally good style to declare non-modifiable string pointers to be of type Hconst char *@, since this often allows the C compiler to detect accidental modifications as well as providing some amount of documentation about what your program intends to do with the string.
The amount of memory allocated for the character array may extend past the null character that normally marks the end of the string. In this document, the term Ballocation size@ is always used to refer to the total amount of memory allocated for the string, while the term Blength@ refers to the number of characters up to (but not including) the terminating null character. ‰IDX347Š‰IDX348Š‰IDX349Š‰IDX350Š‰IDX351Š
@�”˜A notorious source of program bugs is trying to put more characters in a string than fit in its allocated size. When writing code that extends strings or moves characters into a pre-allocated array, you should be very careful to keep track of the length of the text and make explicit checks for overflowing the array. Many of the library functions Bdo not@ do this for you! Remember also that you need to allocate an extra byte to hold the null character that marks the end of the string.
ˆ‰SEC59Št�”›String and Array Conventions

@�”˜This chapter describes both functions that work on arbitrary arrays or blocks of memory, and functions that are specific to null-terminated arrays of characters.
Functions that operate on arbitrary blocks of memory have names beginning with H`mem'@ (such as Hmemcpy@) and invariably take an argument which specifies the size (in bytes) of the block of memory to operate on. The array arguments and return values for these functions have type Hvoid *@, and as a matter of style, the elements of these arrays are referred to as "bytes". You can pass any kind of pointer to these functions, and the Hsizeof@ operator is useful in computing the value for the size argument.
In contrast, functions that operate specifically on strings have names beginning with H`str'@ (such as Hstrcpy@) and look for a null character to terminate the string instead of requiring an explicit size argument to be passed. (Some of these functions accept a specified maximum length, but they also check for premature termination with a null character.) The array arguments and return values for these functions have type Hchar *@, and the array elements are referred to as "characters".
In many cases, there are both H`mem'@ and H`str'@ versions of a function. The one that is more appropriate to use depends on the exact situation. When your program is manipulating arbitrary arrays or blocks of storage, then you should always use the H`mem'@ functions. On the other hand, when you are manipulating null-terminated strings it is usually more convenient to use the H`str'@ functions, unless you already know the length of the string in advance.
ˆ‰SEC60Št�”›String Length

@�”˜You can get the length of a string using the Hstrlen@ function. This function is declared in the header file H`string.h'@. ‰IDX352Š

A�”˜Function:@ size_t Dstrlen@ B(const char *Bs@)
Â‰IDX353Š@�”˜The Hstrlen@ function returns the length of the null-terminated string Bs@. (In other words, it returns the offset of the terminating null character within the array.)
For example, strlen ("hello, world")
=> 12
When applied to a character array, the Hstrlen@ function returns the length of the string stored there, not its allocation size. You can get the allocation size of the character array that holds a string using the Hsizeof@ operator: char string[32] = "hello, world";
sizeof (string)
=> 32
strlen (string)
=> 12 À

ˆ‰SEC61Št�”›Copying and Concatenation

@�”˜You can use the functions described in this section to copy the contents of strings and arrays, or to append the contents of one string to another. These functions are declared in the header file H`string.h'@. ‰IDX354Š‰IDX355Š‰IDX356Š‰IDX357Š‰IDX358Š‰IDX359Š
@�”˜A helpful way to remember the ordering of the arguments to the functions in this section is that it corresponds to an assignment expression, with the destination array specified to the left of the source array. All of these functions return the address of the destination array.
Most of these functions do not work properly if the source and destination arrays overlap. For example, if the beginning of the destination array overlaps the end of the source array, the original contents of that part of the source array may get overwritten before it is copied. Even worse, in the case of the string functions, the null character marking the end of the string may be lost, and the copy function might get stuck in a loop trashing all the memory allocated to your program.
All functions that have problems copying between overlapping arrays are explicitly identified in this manual. In addition to functions in this section, there are a few others like Hsprintf@ (see section ‰ŠP�”›Formatted Output Functions@�”˜) and Hscanf@ (see section ‰ŠP�”›Formatted Input Functions@�”˜).

AFunction:@ void * Dmemcpy@ B(void *Bto@, const void *Bfrom@, size_t Bsize@)
Â‰IDX360Š@�”˜The Hmemcpy@ function copies Bsize@ bytes from the object beginning at Bfrom@ into the object beginning at Bto@. The behavior of this function is undefined if the two arrays Bto@ and Bfrom@ overlap; use Hmemmove@ instead if overlapping is possible.
The value returned by Hmemcpy@ is the value of Bto@.
Here is an example of how you might use Hmemcpy@ to copy the contents of an array: struct foo *oldarray, *newarray;
int arraysize;
...
memcpy (new, old, arraysize * sizeof (struct foo)); À

AFunction:@ void * Dmemmove@ B(void *Bto@, const void *Bfrom@, size_t Bsize@)
Â‰IDX361ŠH�”˜memmove@ copies the Bsize@ bytes at Bfrom@ into the Bsize@ bytes at Bto@, even if those two blocks of space overlap. In the case of overlap, Hmemmove@ is careful to copy the original values of the bytes in the block at Bfrom@, including those bytes which also belong to the block at Bto@.À

AFunction:@ void * Dmemccpy@ B(void *Bto@, const void *Bfrom@, int Bc@, size_t Bsize@)
Â‰IDX362Š@�”˜This function copies no more than Bsize@ bytes from Bfrom@ to Bto@, stopping if a byte matching Bc@ is found. The return value is a pointer into Bto@ one byte past where Bc@ was copied, or a null pointer if no byte matching Bc@ appeared in the first Bsize@ bytes of Bfrom@.À

AFunction:@ void * Dmemset@ B(void *Bblock@, int Bc@, size_t Bsize@)
Â‰IDX363Š@�”˜This function copies the value of Bc@ (converted to an Hunsigned char@) into each of the first Bsize@ bytes of the object beginning at Bblock@. It returns the value of Bblock@.À

AFunction:@ char * Dstrcpy@ B(char *Bto@, const char *Bfrom@)
Â‰IDX364Š@�”˜This copies characters from the string Bfrom@ (up to and including the terminating null character) into the string Bto@. Like Hmemcpy@, this function has undefined results if the strings overlap. The return value is the value of Bto@.À

AFunction:@ char * Dstrncpy@ B(char *Bto@, const char *Bfrom@, size_t Bsize@)
Â‰IDX365Š@�”˜This function is similar to Hstrcpy@ but always copies exactly Bsize@ characters into Bto@.
If the length of Bfrom@ is more than Bsize@, then Hstrncpy@ copies just the first Bsize@ characters. Note that in this case there is no null terminator written into Bto@.
If the length of Bfrom@ is less than Bsize@, then Hstrncpy@ copies all of Bfrom@, followed by enough null characters to add up to Bsize@ characters in all. This behavior is rarely useful, but it is specified by the ISO C standard.
The behavior of Hstrncpy@ is undefined if the strings overlap.
Using Hstrncpy@ as opposed to Hstrcpy@ is a way to avoid bugs relating to writing past the end of the allocated space for Bto@. However, it can also make your program much slower in one common case: copying a string which is probably small into a potentially large buffer. In this case, Bsize@ may be large, and when it is, Hstrncpy@ will waste a considerable amount of time copying null characters.À

AFunction:@ char * Dstrdup@ B(const char *Bs@)
Â‰IDX366Š@�”˜This function copies the null-terminated string Bs@ into a newly allocated string. The string is allocated using Hmalloc@; see section ‰ŠP�”›Unconstrained Allocation@�”˜. If Hmalloc@ cannot allocate space for the new string, Hstrdup@ returns a null pointer. Otherwise it returns a pointer to the new string.À

AFunction:@ char * Dstrndup@ B(const char *Bs@, size_t Bsize@)
Â‰IDX367Š@�”˜This function is similar to Hstrdup@ but always copies at most Bsize@ characters into the newly allocated string.
If the length of Bs@ is more than Bsize@, then Hstrndup@ copies just the first Bsize@ characters and adds a closing null terminator. Otherwise all characters are copied and the string is terminated.
This function is different to Hstrncpy@ in that it always terminates the destination string.À

AFunction:@ char * Dstpcpy@ B(char *Bto@, const char *Bfrom@)
Â‰IDX368Š@�”˜This function is like Hstrcpy@, except that it returns a pointer to the end of the string Bto@ (that is, the address of the terminating null character) rather than the beginning.
For example, this program uses Hstpcpy@ to concatenate H`foo'@ and H`bar'@ to produce H`foobar'@, which it then prints. #include <string.h>
#include <stdio.h>

int
main (void)
{
char buffer[10];
char *to = buffer;
to = stpcpy (to, "foo");
to = stpcpy (to, "bar");
puts (buffer);
return 0;
}
This function is not part of the ISO or POSIX standards, and is not customary on Unix systems, but we did not invent it either. Perhaps it comes from MS-DOG.
Its behavior is undefined if the strings overlap.À

AFunction:@ char * Dstpncpy@ B(char *Bto@, const char *Bfrom@, size_t Bsize@)
Â‰IDX369Š@�”˜This function is similar to Hstpcpy@ but copies always exactly Bsize@ characters into Bto@.
If the length of Bfrom@ is more then Bsize@, then Hstpncpy@ copies just the first Bsize@ characters and returns a pointer to the character directly following the one which was copied last. Note that in this case there is no null terminator written into Bto@.
If the length of Bfrom@ is less than Bsize@, then Hstpncpy@ copies all of Bfrom@, followed by enough null characters to add up to Bsize@ characters in all. This behaviour is rarely useful, but it is implemented to be useful in contexts where this behaviour of the Hstrncpy@ is used. Hstpncpy@ returns a pointer to the Bfirst@ written null character.
This function is not part of ISO or POSIX but was found useful while developing GNU C Library itself.
Its behaviour is undefined if the strings overlap.À

AFunction:@ char * Dstrdupa@ B(const char *Bs@)
Â‰IDX370Š@�”˜This function is similar to Hstrdup@ but allocates the new string using Halloca@ instead of Hmalloc@ see section ‰ŠP�”›Automatic Storage with Variable Size@�”˜. This means of course the returned string has the same limitations as any block of memory allocated using Halloca@.
For obvious reasons Hstrdupa@ is implemented only as a macro. I.e., you cannot get the address of this function. Despite this limitations it is a useful function. The following code shows a situation where using Hmalloc@ would be a lot more expensive. #include <paths.h>
#include <string.h>
#include <stdio.h>

const char path[] = _PATH_STDPATH;

int
main (void)
{
char *wr_path = strdupa (path);
char *cp = strtok (wr_path, ":");

while (cp != NULL)
{
puts (cp);
cp = strtok (NULL, ":");
}
return 0;
}
Please note that calling Hstrtok@ using Bpath@ directly is illegal.
This function is only available if GNU CC is used.À

AFunction:@ char * Dstrndupa@ B(const char *Bs@, size_t Bsize@)
Â‰IDX371Š@�”˜This function is similar to Hstrndup@ but like Hstrdupa@ it allocates the new string using Halloca@ see section ‰ŠP�”›Automatic Storage with Variable Size@�”˜. The same advantages and limitations of Hstrdupa@ are valid for Hstrndupa@, too.
This function is implemented only as a macro which means one cannot get the address of it.
Hstrndupa@ is only available if GNU CC is used.À

AFunction:@ char * Dstrcat@ B(char *Bto@, const char *Bfrom@)
Â‰IDX372Š@�”˜The Hstrcat@ function is similar to Hstrcpy@, except that the characters from Bfrom@ are concatenated or appended to the end of Bto@, instead of overwriting it. That is, the first character from Bfrom@ overwrites the null character marking the end of Bto@.
An equivalent definition for Hstrcat@ would be: char *
strcat (char *to, const char *from)
{
strcpy (to + strlen (to), from);
return to;
}
This function has undefined results if the strings overlap.À

AFunction:@ char * Dstrncat@ B(char *Bto@, const char *Bfrom@, size_t Bsize@)
Â‰IDX373Š@�”˜This function is like Hstrcat@ except that not more than Bsize@ characters from Bfrom@ are appended to the end of Bto@. A single null character is also always appended to Bto@, so the total allocated size of Bto@ must be at least JsizeH + 1@ bytes longer than its initial length.
The Hstrncat@ function could be implemented like this: char *
strncat (char *to, const char *from, size_t size)
{
strncpy (to + strlen (to), from, size);
return to;
}
The behavior of Hstrncat@ is undefined if the strings overlap.À

Here is an example showing the use of Hstrncpy@ and Hstrncat@. Notice how, in the call to Hstrncat@, the Bsize@ parameter is computed to avoid overflowing the character array Hbuffer@. #include <string.h>
#include <stdio.h>

#define SIZE 10

static char buffer[SIZE];

main ()
{
strncpy (buffer, "hello", SIZE);
puts (buffer);
strncat (buffer, ", world", SIZE - strlen (buffer) - 1);
puts (buffer);
}
The output produced by this program looks like: hello
hello, wo

AFunction:@ void * Dbcopy@ B(void *Bfrom@, const void *Bto@, size_t Bsize@)
Â‰IDX374Š@�”˜This is a partially obsolete alternative for Hmemmove@, derived from BSD. Note that it is not quite equivalent to Hmemmove@, because the arguments are not in the same order.À

AFunction:@ void * Dbzero@ B(void *Bblock@, size_t Bsize@)
Â‰IDX375Š@�”˜This is a partially obsolete alternative for Hmemset@, derived from BSD. Note that it is not as general as Hmemset@, because the only value it can store is zero.À

ˆ‰SEC62Št�”›String/Array Comparison

‰IDX376Š‰IDX377Š‰IDX378Š‰IDX379Š‰IDX380Š
@�”˜You can use the functions in this section to perform comparisons on the contents of strings and arrays. As well as checking for equality, these functions can also be used as the ordering functions for sorting operations. See section ‰ŠP�”›Searching and Sorting@�”˜, for an example of this.
Unlike most comparison operations in C, the string comparison functions return a nonzero value if the strings are Bnot@ equivalent rather than if they are. The sign of the value indicates the relative ordering of the first characters in the strings that are not equivalent: a negative value indicates that the first string is "less" than the second, while a positive value indicates that the first string is "greater".
The most common use of these functions is to check only for equality. This is canonically done with an expression like H`! strcmp (s1, s2)'@.
All of these functions are declared in the header file H`string.h'@. ‰IDX381Š

A�”˜Function:@ int Dmemcmp@ B(const void *Ba1@, const void *Ba2@, size_t Bsize@)
Â‰IDX382Š@�”˜The function Hmemcmp@ compares the Bsize@ bytes of memory beginning at Ba1@ against the Bsize@ bytes of memory beginning at Ba2@. The value returned has the same sign as the difference between the first differing pair of bytes (interpreted as Hunsigned char@ objects, then promoted to Hint@).
If the contents of the two blocks are equal, Hmemcmp@ returns H0@.À

On arbitrary arrays, the Hmemcmp@ function is mostly useful for testing equality. It usually isn't meaningful to do byte-wise ordering comparisons on arrays of things other than bytes. For example, a byte-wise comparison on the bytes that make up floating-point numbers isn't likely to tell you anything about the relationship between the values of the floating-point numbers.
You should also be careful about using Hmemcmp@ to compare objects that can contain "holes", such as the padding inserted into structure objects to enforce alignment requirements, extra space at the end of unions, and extra characters at the ends of strings whose length is less than their allocated size. The contents of these "holes" are indeterminate and may cause strange behavior when performing byte-wise comparisons. For more predictable results, perform an explicit component-wise comparison.
For example, given a structure type definition like: struct foo
{
unsigned char tag;
union
{
double f;
long i;
char *p;
} value;
};
you are better off writing a specialized comparison function to compare Hstruct foo@ objects instead of comparing them with Hmemcmp@.

AFunction:@ int Dstrcmp@ B(const char *Bs1@, const char *Bs2@)
Â‰IDX383Š@�”˜The Hstrcmp@ function compares the string Bs1@ against Bs2@, returning a value that has the same sign as the difference between the first differing pair of characters (interpreted as Hunsigned char@ objects, then promoted to Hint@).
If the two strings are equal, Hstrcmp@ returns H0@.
A consequence of the ordering used by Hstrcmp@ is that if Bs1@ is an initial substring of Bs2@, then Bs1@ is considered to be "less than" Bs2@.À

AFunction:@ int Dstrcasecmp@ B(const char *Bs1@, const char *Bs2@)
Â‰IDX384Š@�”˜This function is like Hstrcmp@, except that differences in case are ignored.
Hstrcasecmp@ is derived from BSD.À

AFunction:@ int Dstrncasecmp@ B(const char *Bs1@, const char *Bs2@, size_t Bn@)
Â‰IDX385Š@�”˜This function is like Hstrncmp@, except that differences in case are ignored.
Hstrncasecmp@ is a GNU extension.À

AFunction:@ int Dstrncmp@ B(const char *Bs1@, const char *Bs2@, size_t Bsize@)
Â‰IDX386Š@�”˜This function is the similar to Hstrcmp@, except that no more than Bsize@ characters are compared. In other words, if the two strings are the same in their first Bsize@ characters, the return value is zero.À

Here are some examples showing the use of Hstrcmp@ and Hstrncmp@. These examples assume the use of the ASCII character set. (If some other character set--say, EBCDIC--is used instead, then the glyphs are associated with different numeric codes, and the return values and ordering may differ.) strcmp ("hello", "hello")
=> 0 /* These two strings are the same. */
strcmp ("hello", "Hello")
=> 32 /* Comparisons are case-sensitive. */
strcmp ("hello", "world")
=> -15 /* The character H'h'@ comes before H'w'@. */
strcmp ("hello", "hello, world")
=> -44 /* Comparing a null character against a comma. */
strncmp ("hello", "hello, world", 5)
=> 0 /* The initial 5 characters are the same. */
strncmp ("hello, world", "hello, stupid world!!!", 5)
=> 0 /* The initial 5 characters are the same. */

AFunction:@ int Dbcmp@ B(const void *Ba1@, const void *Ba2@, size_t Bsize@)
Â‰IDX387Š@�”˜This is an obsolete alias for Hmemcmp@, derived from BSD.À

ˆ‰SEC63Št�”›Collation Functions

‰IDX388Š‰IDX389Š
@�”˜In some locales, the conventions for lexicographic ordering differ from the strict numeric ordering of character codes. For example, in Spanish most glyphs with diacritical marks such as accents are not considered distinct letters for the purposes of collation. On the other hand, the two-character sequence H`ll'@ is treated as a single letter that is collated immediately after H`l'@.
You can use the functions Hstrcoll@ and Hstrxfrm@ (declared in the header file H`string.h'@) to compare strings using a collation ordering appropriate for the current locale. The locale used by these functions in particular can be specified by setting the locale for the HLC_COLLATE@ category; see section ‰ŠP�”›Locales and Internationalization@�”˜. ‰IDX390Š
@�”˜In the standard C locale, the collation sequence for Hstrcoll@ is the same as that for Hstrcmp@.
Effectively, the way these functions work is by applying a mapping to transform the characters in a string to a byte sequence that represents the string's position in the collating sequence of the current locale. Comparing two such byte sequences in a simple fashion is equivalent to comparing the strings with the locale's collating sequence.
The function Hstrcoll@ performs this translation implicitly, in order to do one comparison. By contrast, Hstrxfrm@ performs the mapping explicitly. If you are making multiple comparisons using the same string or set of strings, it is likely to be more efficient to use Hstrxfrm@ to transform all the strings just once, and subsequently compare the transformed strings with Hstrcmp@.

AFunction:@ int Dstrcoll@ B(const char *Bs1@, const char *Bs2@)
Â‰IDX391Š@�”˜The Hstrcoll@ function is similar to Hstrcmp@ but uses the collating sequence of the current locale for collation (the HLC_COLLATE@ locale).À

Here is an example of sorting an array of strings, using Hstrcoll@ to compare them. The actual sort algorithm is not written here; it comes from Hqsort@ (see section ‰ŠP�”›Array Sort Function@�”˜). The job of the code shown here is to say how to compare the strings while sorting them. (Later on in this section, we will show a way to do this more efficiently using Hstrxfrm@.) /* This is the comparison function used with Hqsort@. */

int
compare_elements (char **p1, char **p2)
{
return strcoll (*p1, *p2);
}

/* This is the entry point---the function to sort
strings using the locale's collating sequence. */

void
sort_strings (char **array, int nstrings)
{
/* Sort Htemp_array@ by comparing the strings. */
qsort (array, sizeof (char *),
nstrings, compare_elements);
}
‰IDX392Š
A�”˜Function:@ size_t Dstrxfrm@ B(char *Bto@, const char *Bfrom@, size_t Bsize@)
Â‰IDX393Š@�”˜The function Hstrxfrm@ transforms Bstring@ using the collation transformation determined by the locale currently selected for collation, and stores the transformed string in the array Bto@. Up to Bsize@ characters (including a terminating null character) are stored.
The behavior is undefined if the strings Bto@ and Bfrom@ overlap; see section ‰ŠP�”›Copying and Concatenation@�”˜.
The return value is the length of the entire transformed string. This value is not affected by the value of Bsize@, but if it is greater or equal than Bsize@, it means that the transformed string did not entirely fit in the array Bto@. In this case, only as much of the string as actually fits was stored. To get the whole transformed string, call Hstrxfrm@ again with a bigger output array.
The transformed string may be longer than the original string, and it may also be shorter.
If Bsize@ is zero, no characters are stored in Bto@. In this case, Hstrxfrm@ simply returns the number of characters that would be the length of the transformed string. This is useful for determining what size string to allocate. It does not matter what Bto@ is if Bsize@ is zero; Bto@ may even be a null pointer.À

Here is an example of how you can use Hstrxfrm@ when you plan to do many comparisons. It does the same thing as the previous example, but much faster, because it has to transform each string only once, no matter how many times it is compared with other strings. Even the time needed to allocate and free storage is much less than the time we save, when there are many strings. struct sorter { char *input; char *transformed; };

/* This is the comparison function used with Hqsort
@ to sort an array of Hstruct sorter@. */

int
compare_elements (struct sorter *p1, struct sorter *p2)
{
return strcmp (p1->transformed, p2->transformed);
}

/* This is the entry point---the function to sort
strings using the locale's collating sequence. */

void
sort_strings_fast (char **array, int nstrings)
{
struct sorter temp_array[nstrings];
int i;

/* Set up Htemp_array@. Each element contains
one input string and its transformed string. */
for (i = 0; i < nstrings; i++)
{
size_t length = strlen (array[i]) * 2;
char *transformed;
size_t transformed_lenght;

temp_array[i].input = array[i];

/* First try a buffer perhaps big enough. */
transformed = (char *) xmalloc (length);

/* Transform Harray[i]@. */
transformed_length = strxfrm (transformed, array[i], length);

/* If the buffer was not large enough, resize it
and try again. */
if (transformed_length >= length)
{
/* Allocate the needed space. +1 for terminating
HNUL@ character. */
transformed = (char *) xrealloc (transformed,
transformed_length + 1);

/* The return value is not interesting because we know
how long the transformed string is. */
(void) strxfrm (transformed, array[i], transformed_length + 1);
}

temp_array[i].transformed = transformed;
}

/* Sort Htemp_array@ by comparing transformed strings. */
qsort (temp_array, sizeof (struct sorter),
nstrings, compare_elements);

/* Put the elements back in the permanent array
in their sorted order. */
for (i = 0; i < nstrings; i++)
array[i] = temp_array[i].input;

/* Free the strings we allocated. */
for (i = 0; i < nstrings; i++)
free (temp_array[i].transformed);
}
DCompatibility Note:@ The string collation functions are a new feature of ISO C. Older C dialects have no equivalent feature.
ˆ‰SEC64Št�”›Search Functions

@�”˜This section describes library functions which perform various kinds of searching operations on strings and arrays. These functions are declared in the header file H`string.h'@. ‰IDX394Š‰IDX395Š‰IDX396Š

A�”˜Function:@ void * Dmemchr@ B(const void *Bblock@, int Bc@, size_t Bsize@)
Â‰IDX397Š@�”˜This function finds the first occurrence of the byte Bc@ (converted to an Hunsigned char@) in the initial Bsize@ bytes of the object beginning at Bblock@. The return value is a pointer to the located byte, or a null pointer if no match was found.À

AFunction:@ char * Dstrchr@ B(const char *Bstring@, int Bc@)
Â‰IDX398Š@�”˜The Hstrchr@ function finds the first occurrence of the character Bc@ (converted to a Hchar@) in the null-terminated string beginning at Bstring@. The return value is a pointer to the located character, or a null pointer if no match was found.
For example, strchr ("hello, world", 'l')
=> "llo, world"
strchr ("hello, world", '?')
=> NULL
The terminating null character is considered to be part of the string, so you can use this function get a pointer to the end of a string by specifying a null character as the value of the Bc@ argument.À

AFunction:@ char * Dindex@ B(const char *Bstring@, int Bc@)
Â‰IDX399ŠH�”˜index@ is another name for Hstrchr@; they are exactly the same.À

AFunction:@ char * Dstrrchr@ B(const char *Bstring@, int Bc@)
Â‰IDX400Š@�”˜The function Hstrrchr@ is like Hstrchr@, except that it searches backwards from the end of the string Bstring@ (instead of forwards from the front).
For example, strrchr ("hello, world", 'l')
=> "ld" À

AFunction:@ char * Drindex@ B(const char *Bstring@, int Bc@)
Â‰IDX401ŠH�”˜rindex@ is another name for Hstrrchr@; they are exactly the same.À

AFunction:@ char * Dstrstr@ B(const char *Bhaystack@, const char *Bneedle@)
Â‰IDX402Š@�”˜This is like Hstrchr@, except that it searches Bhaystack@ for a substring Bneedle@ rather than just a single character. It returns a pointer into the string Bhaystack@ that is the first character of the substring, or a null pointer if no match was found. If Bneedle@ is an empty string, the function returns Bhaystack@.
For example, strstr ("hello, world", "l")
=> "llo, world"
strstr ("hello, world", "wo")
=> "world" À

AFunction:@ void * Dmemmem@ B(const void *Bhaystack@, size_t Bhaystack-len@,
const void *Bneedle@, size_t Bneedle-len@)
Â‰IDX403Š@�”˜This is like Hstrstr@, but Bneedle@ and Bhaystack@ are byte arrays rather than null-terminated strings. Bneedle-len@ is the length of Bneedle@ and Bhaystack-len@ is the length of Bhaystack@.
This function is a GNU extension.À

AFunction:@ size_t Dstrspn@ B(const char *Bstring@, const char *Bskipset@)
Â‰IDX404Š@�”˜The Hstrspn@ ("string span") function returns the length of the initial substring of Bstring@ that consists entirely of characters that are members of the set specified by the string Bskipset@. The order of the characters in Bskipset@ is not important.
For example, strspn ("hello, world", "abcdefghijklmnopqrstuvwxyz")
=> 5 À

AFunction:@ size_t Dstrcspn@ B(const char *Bstring@, const char *Bstopset@)
Â‰IDX405Š@�”˜The Hstrcspn@ ("string complement span") function returns the length of the initial substring of Bstring@ that consists entirely of characters that are Bnot@ members of the set specified by the string Bstopset@. (In other words, it returns the offset of the first character in Bstring@ that is a member of the set Bstopset@.)
For example, strcspn ("hello, world", " \t\n,.;!?")
=> 5 À

AFunction:@ char * Dstrpbrk@ B(const char *Bstring@, const char *Bstopset@)
Â‰IDX406Š@�”˜The Hstrpbrk@ ("string pointer break") function is related to Hstrcspn@, except that it returns a pointer to the first character in Bstring@ that is a member of the set Bstopset@ instead of the length of the initial substring. It returns a null pointer if no such character from Bstopset@ is found.
For example, strpbrk ("hello, world", " \t\n,.;!?")
=> ", world" À

ˆ‰SEC65Št�”›Finding Tokens in a String

‰IDX407Š‰IDX408Š‰IDX409Š@�”˜It's fairly common for programs to have a need to do some simple kinds of lexical analysis and parsing, such as splitting a command string up into tokens. You can do this with the Hstrtok@ function, declared in the header file H`string.h'@. ‰IDX410Š

A�”˜Function:@ char * Dstrtok@ B(char *Bnewstring@, const char *Bdelimiters@)
Â‰IDX411Š@�”˜A string can be split into tokens by making a series of calls to the function Hstrtok@.
The string to be split up is passed as the Bnewstring@ argument on the first call only. The Hstrtok@ function uses this to set up some internal state information. Subsequent calls to get additional tokens from the same string are indicated by passing a null pointer as the Bnewstring@ argument. Calling Hstrtok@ with another non-null Bnewstring@ argument reinitializes the state information. It is guaranteed that no other library function ever calls Hstrtok@ behind your back (which would mess up this internal state information).
The Bdelimiters@ argument is a string that specifies a set of delimiters that may surround the token being extracted. All the initial characters that are members of this set are discarded. The first character that is Bnot@ a member of this set of delimiters marks the beginning of the next token. The end of the token is found by looking for the next character that is a member of the delimiter set. This character in the original string Bnewstring@ is overwritten by a null character, and the pointer to the beginning of the token in Bnewstring@ is returned.
On the next call to Hstrtok@, the searching begins at the next character beyond the one that marked the end of the previous token. Note that the set of delimiters Bdelimiters@ do not have to be the same on every call in a series of calls to Hstrtok@.
If the end of the string Bnewstring@ is reached, or if the remainder of string consists only of delimiter characters, Hstrtok@ returns a null pointer.À

DWarning:@ Since Hstrtok@ alters the string it is parsing, you always copy the string to a temporary buffer before parsing it with Hstrtok@. If you allow Hstrtok@ to modify a string that came from another part of your program, you are asking for trouble; that string may be part of a data structure that could be used for other purposes during the parsing, when alteration by Hstrtok@ makes the data structure temporarily inaccurate.
The string that you are operating on might even be a constant. Then when Hstrtok@ tries to modify it, your program will get a fatal signal for writing in read-only memory. See section ‰ŠP�”›Program Error Signals@�”˜.
This is a special case of a general principle: if a part of a program does not have as its purpose the modification of a certain data structure, then it is error-prone to modify the data structure temporarily.
The function Hstrtok@ is not reentrant. See section ‰ŠP�”›Signal Handling and Nonreentrant Functions@�”˜, for a discussion of where and why reentrancy is important.
Here is a simple example showing the use of Hstrtok@. #include <string.h>
#include <stddef.h>

...

char string[] = "words separated by spaces -- and, punctuation!";
const char delimiters[] = " .,;:!-";
char *token;

...

token = strtok (string, delimiters); /* token => "words" */
token = strtok (NULL, delimiters); /* token => "separated" */
token = strtok (NULL, delimiters); /* token => "by" */
token = strtok (NULL, delimiters); /* token => "spaces" */
token = strtok (NULL, delimiters); /* token => "and" */
token = strtok (NULL, delimiters); /* token => "punctuation" */
token = strtok (NULL, delimiters); /* token => NULL */
The GNU C library contains two more functions for tokenizing a string which overcome the limitation of non-reentrancy.

AFunction:@ char * Dstrtok_r@ B(char *Bnewstring@, const char *Bdelimiters@, char **Bsave_ptr@)
Â‰IDX412Š@�”˜Just like Hstrtok@ this function splits the string into several tokens which can be accessed be successive calls to Hstrtok_r@. The difference is that the information about the next token is not set up in some internal state information. Instead the caller has to provide another argument Bsave_ptr@ which is a pointer to a string pointer. Calling Hstrtok_r@ with a null pointer for Bnewstring@ and leaving Bsave_ptr@ between the calls unchanged does the job without limiting reentrancy.
This function was proposed for POSIX.1b and can be found on many systems which support multi-threading.À

AFunction:@ char * Dstrsep@ B(char **Bstring_ptr@, const char *Bdelimiter@)
Â‰IDX413Š@�”˜A second reentrant approach is to avoid the additional first argument. The initialization of the moving pointer has to be done by the user. Successive calls of Hstrsep@ move the pointer along the tokens separated by Bdelimiter@, returning the address of the next token and updating Bstring_ptr@ to point to the beginning of the next token.
This function was introduced in 4.3BSD and therefore is widely available.À

Here is how the above example looks like when Hstrsep@ is used. #include <string.h>
#include <stddef.h>

...

char string[] = "words separated by spaces -- and, punctuation!";
const char delimiters[] = " .,;:!-";
char *running;
char *token;

...

running = string;
token = strsep (&running, delimiters); /* token => "words" */
token = strsep (&running, delimiters); /* token => "separated" */
token = strsep (&running, delimiters); /* token => "by" */
token = strsep (&running, delimiters); /* token => "spaces" */
token = strsep (&running, delimiters); /* token => "and" */
token = strsep (&running, delimiters); /* token => "punctuation" */
token = strsep (&running, delimiters); /* token => NULL */
Œ
Go to the ‰ŠP�”›first@�”˜, ‰ŠP�”›previous@�”˜, ‰ŠP�”›next@�”˜, ‰ŠP�”›last@�”˜ section, ‰ŠP�”›table of contents@�”˜.