]> git.ipfire.org Git - thirdparty/glibc.git/blob - manual/string.texi
initial import
[thirdparty/glibc.git] / manual / string.texi
1 @node String and Array Utilities, Extended Characters, Character Handling, Top
2 @chapter String and Array Utilities
3
4 Operations on strings (or arrays of characters) are an important part of
5 many programs. The GNU C library provides an extensive set of string
6 utility functions, including functions for copying, concatenating,
7 comparing, and searching strings. Many of these functions can also
8 operate on arbitrary regions of storage; for example, the @code{memcpy}
9 function can be used to copy the contents of any kind of array.
10
11 It's fairly common for beginning C programmers to ``reinvent the wheel''
12 by duplicating this functionality in their own code, but it pays to
13 become familiar with the library functions and to make use of them,
14 since this offers benefits in maintenance, efficiency, and portability.
15
16 For instance, you could easily compare one string to another in two
17 lines of C code, but if you use the built-in @code{strcmp} function,
18 you're less likely to make a mistake. And, since these library
19 functions are typically highly optimized, your program may run faster
20 too.
21
22 @menu
23 * Representation of Strings:: Introduction to basic concepts.
24 * String/Array Conventions:: Whether to use a string function or an
25 arbitrary array function.
26 * String Length:: Determining the length of a string.
27 * Copying and Concatenation:: Functions to copy the contents of strings
28 and arrays.
29 * String/Array Comparison:: Functions for byte-wise and character-wise
30 comparison.
31 * Collation Functions:: Functions for collating strings.
32 * Search Functions:: Searching for a specific element or substring.
33 * Finding Tokens in a String:: Splitting a string into tokens by looking
34 for delimiters.
35 @end menu
36
37 @node Representation of Strings, String/Array Conventions, , String and Array Utilities
38 @section Representation of Strings
39 @cindex string, representation of
40
41 This section is a quick summary of string concepts for beginning C
42 programmers. It describes how character strings are represented in C
43 and some common pitfalls. If you are already familiar with this
44 material, you can skip this section.
45
46 @cindex string
47 @cindex null character
48 A @dfn{string} is an array of @code{char} objects. But string-valued
49 variables are usually declared to be pointers of type @code{char *}.
50 Such variables do not include space for the text of a string; that has
51 to be stored somewhere else---in an array variable, a string constant,
52 or dynamically allocated memory (@pxref{Memory Allocation}). It's up to
53 you to store the address of the chosen memory space into the pointer
54 variable. Alternatively you can store a @dfn{null pointer} in the
55 pointer variable. The null pointer does not point anywhere, so
56 attempting to reference the string it points to gets an error.
57
58 By convention, a @dfn{null character}, @code{'\0'}, marks the end of a
59 string. For example, in testing to see whether the @code{char *}
60 variable @var{p} points to a null character marking the end of a string,
61 you can write @code{!*@var{p}} or @code{*@var{p} == '\0'}.
62
63 A null character is quite different conceptually from a null pointer,
64 although both are represented by the integer @code{0}.
65
66 @cindex string literal
67 @dfn{String literals} appear in C program source as strings of
68 characters between double-quote characters (@samp{"}). In ANSI C,
69 string literals can also be formed by @dfn{string concatenation}:
70 @code{"a" "b"} is the same as @code{"ab"}. Modification of string
71 literals is not allowed by the GNU C compiler, because literals
72 are placed in read-only storage.
73
74 Character arrays that are declared @code{const} cannot be modified
75 either. It's generally good style to declare non-modifiable string
76 pointers to be of type @code{const char *}, since this often allows the
77 C compiler to detect accidental modifications as well as providing some
78 amount of documentation about what your program intends to do with the
79 string.
80
81 The amount of memory allocated for the character array may extend past
82 the null character that normally marks the end of the string. In this
83 document, the term @dfn{allocation size} is always used to refer to the
84 total amount of memory allocated for the string, while the term
85 @dfn{length} refers to the number of characters up to (but not
86 including) the terminating null character.
87 @cindex length of string
88 @cindex allocation size of string
89 @cindex size of string
90 @cindex string length
91 @cindex string allocation
92
93 A notorious source of program bugs is trying to put more characters in a
94 string than fit in its allocated size. When writing code that extends
95 strings or moves characters into a pre-allocated array, you should be
96 very careful to keep track of the length of the text and make explicit
97 checks for overflowing the array. Many of the library functions
98 @emph{do not} do this for you! Remember also that you need to allocate
99 an extra byte to hold the null character that marks the end of the
100 string.
101
102 @node String/Array Conventions, String Length, Representation of Strings, String and Array Utilities
103 @section String and Array Conventions
104
105 This chapter describes both functions that work on arbitrary arrays or
106 blocks of memory, and functions that are specific to null-terminated
107 arrays of characters.
108
109 Functions that operate on arbitrary blocks of memory have names
110 beginning with @samp{mem} (such as @code{memcpy}) and invariably take an
111 argument which specifies the size (in bytes) of the block of memory to
112 operate on. The array arguments and return values for these functions
113 have type @code{void *}, and as a matter of style, the elements of these
114 arrays are referred to as ``bytes''. You can pass any kind of pointer
115 to these functions, and the @code{sizeof} operator is useful in
116 computing the value for the size argument.
117
118 In contrast, functions that operate specifically on strings have names
119 beginning with @samp{str} (such as @code{strcpy}) and look for a null
120 character to terminate the string instead of requiring an explicit size
121 argument to be passed. (Some of these functions accept a specified
122 maximum length, but they also check for premature termination with a
123 null character.) The array arguments and return values for these
124 functions have type @code{char *}, and the array elements are referred
125 to as ``characters''.
126
127 In many cases, there are both @samp{mem} and @samp{str} versions of a
128 function. The one that is more appropriate to use depends on the exact
129 situation. When your program is manipulating arbitrary arrays or blocks of
130 storage, then you should always use the @samp{mem} functions. On the
131 other hand, when you are manipulating null-terminated strings it is
132 usually more convenient to use the @samp{str} functions, unless you
133 already know the length of the string in advance.
134
135 @node String Length, Copying and Concatenation, String/Array Conventions, String and Array Utilities
136 @section String Length
137
138 You can get the length of a string using the @code{strlen} function.
139 This function is declared in the header file @file{string.h}.
140 @pindex string.h
141
142 @comment string.h
143 @comment ANSI
144 @deftypefun size_t strlen (const char *@var{s})
145 The @code{strlen} function returns the length of the null-terminated
146 string @var{s}. (In other words, it returns the offset of the terminating
147 null character within the array.)
148
149 For example,
150 @smallexample
151 strlen ("hello, world")
152 @result{} 12
153 @end smallexample
154
155 When applied to a character array, the @code{strlen} function returns
156 the length of the string stored there, not its allocation size. You can
157 get the allocation size of the character array that holds a string using
158 the @code{sizeof} operator:
159
160 @smallexample
161 char string[32] = "hello, world";
162 sizeof (string)
163 @result{} 32
164 strlen (string)
165 @result{} 12
166 @end smallexample
167 @end deftypefun
168
169 @node Copying and Concatenation, String/Array Comparison, String Length, String and Array Utilities
170 @section Copying and Concatenation
171
172 You can use the functions described in this section to copy the contents
173 of strings and arrays, or to append the contents of one string to
174 another. These functions are declared in the header file
175 @file{string.h}.
176 @pindex string.h
177 @cindex copying strings and arrays
178 @cindex string copy functions
179 @cindex array copy functions
180 @cindex concatenating strings
181 @cindex string concatenation functions
182
183 A helpful way to remember the ordering of the arguments to the functions
184 in this section is that it corresponds to an assignment expression, with
185 the destination array specified to the left of the source array. All
186 of these functions return the address of the destination array.
187
188 Most of these functions do not work properly if the source and
189 destination arrays overlap. For example, if the beginning of the
190 destination array overlaps the end of the source array, the original
191 contents of that part of the source array may get overwritten before it
192 is copied. Even worse, in the case of the string functions, the null
193 character marking the end of the string may be lost, and the copy
194 function might get stuck in a loop trashing all the memory allocated to
195 your program.
196
197 All functions that have problems copying between overlapping arrays are
198 explicitly identified in this manual. In addition to functions in this
199 section, there are a few others like @code{sprintf} (@pxref{Formatted
200 Output Functions}) and @code{scanf} (@pxref{Formatted Input
201 Functions}).
202
203 @comment string.h
204 @comment ANSI
205 @deftypefun {void *} memcpy (void *@var{to}, const void *@var{from}, size_t @var{size})
206 The @code{memcpy} function copies @var{size} bytes from the object
207 beginning at @var{from} into the object beginning at @var{to}. The
208 behavior of this function is undefined if the two arrays @var{to} and
209 @var{from} overlap; use @code{memmove} instead if overlapping is possible.
210
211 The value returned by @code{memcpy} is the value of @var{to}.
212
213 Here is an example of how you might use @code{memcpy} to copy the
214 contents of an array:
215
216 @smallexample
217 struct foo *oldarray, *newarray;
218 int arraysize;
219 @dots{}
220 memcpy (new, old, arraysize * sizeof (struct foo));
221 @end smallexample
222 @end deftypefun
223
224 @comment string.h
225 @comment ANSI
226 @deftypefun {void *} memmove (void *@var{to}, const void *@var{from}, size_t @var{size})
227 @code{memmove} copies the @var{size} bytes at @var{from} into the
228 @var{size} bytes at @var{to}, even if those two blocks of space
229 overlap. In the case of overlap, @code{memmove} is careful to copy the
230 original values of the bytes in the block at @var{from}, including those
231 bytes which also belong to the block at @var{to}.
232 @end deftypefun
233
234 @comment string.h
235 @comment SVID
236 @deftypefun {void *} memccpy (void *@var{to}, const void *@var{from}, int @var{c}, size_t @var{size})
237 This function copies no more than @var{size} bytes from @var{from} to
238 @var{to}, stopping if a byte matching @var{c} is found. The return
239 value is a pointer into @var{to} one byte past where @var{c} was copied,
240 or a null pointer if no byte matching @var{c} appeared in the first
241 @var{size} bytes of @var{from}.
242 @end deftypefun
243
244 @comment string.h
245 @comment ANSI
246 @deftypefun {void *} memset (void *@var{block}, int @var{c}, size_t @var{size})
247 This function copies the value of @var{c} (converted to an
248 @code{unsigned char}) into each of the first @var{size} bytes of the
249 object beginning at @var{block}. It returns the value of @var{block}.
250 @end deftypefun
251
252 @comment string.h
253 @comment ANSI
254 @deftypefun {char *} strcpy (char *@var{to}, const char *@var{from})
255 This copies characters from the string @var{from} (up to and including
256 the terminating null character) into the string @var{to}. Like
257 @code{memcpy}, this function has undefined results if the strings
258 overlap. The return value is the value of @var{to}.
259 @end deftypefun
260
261 @comment string.h
262 @comment ANSI
263 @deftypefun {char *} strncpy (char *@var{to}, const char *@var{from}, size_t @var{size})
264 This function is similar to @code{strcpy} but always copies exactly
265 @var{size} characters into @var{to}.
266
267 If the length of @var{from} is more than @var{size}, then @code{strncpy}
268 copies just the first @var{size} characters. Note that in this case
269 there is no null terminator written into @var{to}.
270
271 If the length of @var{from} is less than @var{size}, then @code{strncpy}
272 copies all of @var{from}, followed by enough null characters to add up
273 to @var{size} characters in all. This behavior is rarely useful, but it
274 is specified by the ANSI C standard.
275
276 The behavior of @code{strncpy} is undefined if the strings overlap.
277
278 Using @code{strncpy} as opposed to @code{strcpy} is a way to avoid bugs
279 relating to writing past the end of the allocated space for @var{to}.
280 However, it can also make your program much slower in one common case:
281 copying a string which is probably small into a potentially large buffer.
282 In this case, @var{size} may be large, and when it is, @code{strncpy} will
283 waste a considerable amount of time copying null characters.
284 @end deftypefun
285
286 @comment string.h
287 @comment SVID
288 @deftypefun {char *} strdup (const char *@var{s})
289 This function copies the null-terminated string @var{s} into a newly
290 allocated string. The string is allocated using @code{malloc}; see
291 @ref{Unconstrained Allocation}. If @code{malloc} cannot allocate space
292 for the new string, @code{strdup} returns a null pointer. Otherwise it
293 returns a pointer to the new string.
294 @end deftypefun
295
296 @comment string.h
297 @comment Unknown origin
298 @deftypefun {char *} stpcpy (char *@var{to}, const char *@var{from})
299 This function is like @code{strcpy}, except that it returns a pointer to
300 the end of the string @var{to} (that is, the address of the terminating
301 null character) rather than the beginning.
302
303 For example, this program uses @code{stpcpy} to concatenate @samp{foo}
304 and @samp{bar} to produce @samp{foobar}, which it then prints.
305
306 @smallexample
307 @include stpcpy.c.texi
308 @end smallexample
309
310 This function is not part of the ANSI or POSIX standards, and is not
311 customary on Unix systems, but we did not invent it either. Perhaps it
312 comes from MS-DOG.
313
314 Its behavior is undefined if the strings overlap.
315 @end deftypefun
316
317 @comment string.h
318 @comment ANSI
319 @deftypefun {char *} strcat (char *@var{to}, const char *@var{from})
320 The @code{strcat} function is similar to @code{strcpy}, except that the
321 characters from @var{from} are concatenated or appended to the end of
322 @var{to}, instead of overwriting it. That is, the first character from
323 @var{from} overwrites the null character marking the end of @var{to}.
324
325 An equivalent definition for @code{strcat} would be:
326
327 @smallexample
328 char *
329 strcat (char *to, const char *from)
330 @{
331 strcpy (to + strlen (to), from);
332 return to;
333 @}
334 @end smallexample
335
336 This function has undefined results if the strings overlap.
337 @end deftypefun
338
339 @comment string.h
340 @comment ANSI
341 @deftypefun {char *} strncat (char *@var{to}, const char *@var{from}, size_t @var{size})
342 This function is like @code{strcat} except that not more than @var{size}
343 characters from @var{from} are appended to the end of @var{to}. A
344 single null character is also always appended to @var{to}, so the total
345 allocated size of @var{to} must be at least @code{@var{size} + 1} bytes
346 longer than its initial length.
347
348 The @code{strncat} function could be implemented like this:
349
350 @smallexample
351 @group
352 char *
353 strncat (char *to, const char *from, size_t size)
354 @{
355 strncpy (to + strlen (to), from, size);
356 return to;
357 @}
358 @end group
359 @end smallexample
360
361 The behavior of @code{strncat} is undefined if the strings overlap.
362 @end deftypefun
363
364 Here is an example showing the use of @code{strncpy} and @code{strncat}.
365 Notice how, in the call to @code{strncat}, the @var{size} parameter
366 is computed to avoid overflowing the character array @code{buffer}.
367
368 @smallexample
369 @include strncat.c.texi
370 @end smallexample
371
372 @noindent
373 The output produced by this program looks like:
374
375 @smallexample
376 hello
377 hello, wo
378 @end smallexample
379
380 @comment string.h
381 @comment BSD
382 @deftypefun {void *} bcopy (void *@var{from}, const void *@var{to}, size_t @var{size})
383 This is a partially obsolete alternative for @code{memmove}, derived from
384 BSD. Note that it is not quite equivalent to @code{memmove}, because the
385 arguments are not in the same order.
386 @end deftypefun
387
388 @comment string.h
389 @comment BSD
390 @deftypefun {void *} bzero (void *@var{block}, size_t @var{size})
391 This is a partially obsolete alternative for @code{memset}, derived from
392 BSD. Note that it is not as general as @code{memset}, because the only
393 value it can store is zero.
394 @end deftypefun
395
396 @node String/Array Comparison, Collation Functions, Copying and Concatenation, String and Array Utilities
397 @section String/Array Comparison
398 @cindex comparing strings and arrays
399 @cindex string comparison functions
400 @cindex array comparison functions
401 @cindex predicates on strings
402 @cindex predicates on arrays
403
404 You can use the functions in this section to perform comparisons on the
405 contents of strings and arrays. As well as checking for equality, these
406 functions can also be used as the ordering functions for sorting
407 operations. @xref{Searching and Sorting}, for an example of this.
408
409 Unlike most comparison operations in C, the string comparison functions
410 return a nonzero value if the strings are @emph{not} equivalent rather
411 than if they are. The sign of the value indicates the relative ordering
412 of the first characters in the strings that are not equivalent: a
413 negative value indicates that the first string is ``less'' than the
414 second, while a positive value indicates that the first string is
415 ``greater''.
416
417 The most common use of these functions is to check only for equality.
418 This is canonically done with an expression like @w{@samp{! strcmp (s1, s2)}}.
419
420 All of these functions are declared in the header file @file{string.h}.
421 @pindex string.h
422
423 @comment string.h
424 @comment ANSI
425 @deftypefun int memcmp (const void *@var{a1}, const void *@var{a2}, size_t @var{size})
426 The function @code{memcmp} compares the @var{size} bytes of memory
427 beginning at @var{a1} against the @var{size} bytes of memory beginning
428 at @var{a2}. The value returned has the same sign as the difference
429 between the first differing pair of bytes (interpreted as @code{unsigned
430 char} objects, then promoted to @code{int}).
431
432 If the contents of the two blocks are equal, @code{memcmp} returns
433 @code{0}.
434 @end deftypefun
435
436 On arbitrary arrays, the @code{memcmp} function is mostly useful for
437 testing equality. It usually isn't meaningful to do byte-wise ordering
438 comparisons on arrays of things other than bytes. For example, a
439 byte-wise comparison on the bytes that make up floating-point numbers
440 isn't likely to tell you anything about the relationship between the
441 values of the floating-point numbers.
442
443 You should also be careful about using @code{memcmp} to compare objects
444 that can contain ``holes'', such as the padding inserted into structure
445 objects to enforce alignment requirements, extra space at the end of
446 unions, and extra characters at the ends of strings whose length is less
447 than their allocated size. The contents of these ``holes'' are
448 indeterminate and may cause strange behavior when performing byte-wise
449 comparisons. For more predictable results, perform an explicit
450 component-wise comparison.
451
452 For example, given a structure type definition like:
453
454 @smallexample
455 struct foo
456 @{
457 unsigned char tag;
458 union
459 @{
460 double f;
461 long i;
462 char *p;
463 @} value;
464 @};
465 @end smallexample
466
467 @noindent
468 you are better off writing a specialized comparison function to compare
469 @code{struct foo} objects instead of comparing them with @code{memcmp}.
470
471 @comment string.h
472 @comment ANSI
473 @deftypefun int strcmp (const char *@var{s1}, const char *@var{s2})
474 The @code{strcmp} function compares the string @var{s1} against
475 @var{s2}, returning a value that has the same sign as the difference
476 between the first differing pair of characters (interpreted as
477 @code{unsigned char} objects, then promoted to @code{int}).
478
479 If the two strings are equal, @code{strcmp} returns @code{0}.
480
481 A consequence of the ordering used by @code{strcmp} is that if @var{s1}
482 is an initial substring of @var{s2}, then @var{s1} is considered to be
483 ``less than'' @var{s2}.
484 @end deftypefun
485
486 @comment string.h
487 @comment BSD
488 @deftypefun int strcasecmp (const char *@var{s1}, const char *@var{s2})
489 This function is like @code{strcmp}, except that differences in case
490 are ignored.
491
492 @code{strcasecmp} is derived from BSD.
493 @end deftypefun
494
495 @comment string.h
496 @comment BSD
497 @deftypefun int strncasecmp (const char *@var{s1}, const char *@var{s2}, size_t @var{n})
498 This function is like @code{strncmp}, except that differences in case
499 are ignored.
500
501 @code{strncasecmp} is a GNU extension.
502 @end deftypefun
503
504 @comment string.h
505 @comment ANSI
506 @deftypefun int strncmp (const char *@var{s1}, const char *@var{s2}, size_t @var{size})
507 This function is the similar to @code{strcmp}, except that no more than
508 @var{size} characters are compared. In other words, if the two strings are
509 the same in their first @var{size} characters, the return value is zero.
510 @end deftypefun
511
512 Here are some examples showing the use of @code{strcmp} and @code{strncmp}.
513 These examples assume the use of the ASCII character set. (If some
514 other character set---say, EBCDIC---is used instead, then the glyphs
515 are associated with different numeric codes, and the return values
516 and ordering may differ.)
517
518 @smallexample
519 strcmp ("hello", "hello")
520 @result{} 0 /* @r{These two strings are the same.} */
521 strcmp ("hello", "Hello")
522 @result{} 32 /* @r{Comparisons are case-sensitive.} */
523 strcmp ("hello", "world")
524 @result{} -15 /* @r{The character @code{'h'} comes before @code{'w'}.} */
525 strcmp ("hello", "hello, world")
526 @result{} -44 /* @r{Comparing a null character against a comma.} */
527 strncmp ("hello", "hello, world"", 5)
528 @result{} 0 /* @r{The initial 5 characters are the same.} */
529 strncmp ("hello, world", "hello, stupid world!!!", 5)
530 @result{} 0 /* @r{The initial 5 characters are the same.} */
531 @end smallexample
532
533 @comment string.h
534 @comment BSD
535 @deftypefun int bcmp (const void *@var{a1}, const void *@var{a2}, size_t @var{size})
536 This is an obsolete alias for @code{memcmp}, derived from BSD.
537 @end deftypefun
538
539 @node Collation Functions, Search Functions, String/Array Comparison, String and Array Utilities
540 @section Collation Functions
541
542 @cindex collating strings
543 @cindex string collation functions
544
545 In some locales, the conventions for lexicographic ordering differ from
546 the strict numeric ordering of character codes. For example, in Spanish
547 most glyphs with diacritical marks such as accents are not considered
548 distinct letters for the purposes of collation. On the other hand, the
549 two-character sequence @samp{ll} is treated as a single letter that is
550 collated immediately after @samp{l}.
551
552 You can use the functions @code{strcoll} and @code{strxfrm} (declared in
553 the header file @file{string.h}) to compare strings using a collation
554 ordering appropriate for the current locale. The locale used by these
555 functions in particular can be specified by setting the locale for the
556 @code{LC_COLLATE} category; see @ref{Locales}.
557 @pindex string.h
558
559 In the standard C locale, the collation sequence for @code{strcoll} is
560 the same as that for @code{strcmp}.
561
562 Effectively, the way these functions work is by applying a mapping to
563 transform the characters in a string to a byte sequence that represents
564 the string's position in the collating sequence of the current locale.
565 Comparing two such byte sequences in a simple fashion is equivalent to
566 comparing the strings with the locale's collating sequence.
567
568 The function @code{strcoll} performs this translation implicitly, in
569 order to do one comparison. By contrast, @code{strxfrm} performs the
570 mapping explicitly. If you are making multiple comparisons using the
571 same string or set of strings, it is likely to be more efficient to use
572 @code{strxfrm} to transform all the strings just once, and subsequently
573 compare the transformed strings with @code{strcmp}.
574
575 @comment string.h
576 @comment ANSI
577 @deftypefun int strcoll (const char *@var{s1}, const char *@var{s2})
578 The @code{strcoll} function is similar to @code{strcmp} but uses the
579 collating sequence of the current locale for collation (the
580 @code{LC_COLLATE} locale).
581 @end deftypefun
582
583 Here is an example of sorting an array of strings, using @code{strcoll}
584 to compare them. The actual sort algorithm is not written here; it
585 comes from @code{qsort} (@pxref{Array Sort Function}). The job of the
586 code shown here is to say how to compare the strings while sorting them.
587 (Later on in this section, we will show a way to do this more
588 efficiently using @code{strxfrm}.)
589
590 @smallexample
591 /* @r{This is the comparison function used with @code{qsort}.} */
592
593 int
594 compare_elements (char **p1, char **p2)
595 @{
596 return strcoll (*p1, *p2);
597 @}
598
599 /* @r{This is the entry point---the function to sort}
600 @r{strings using the locale's collating sequence.} */
601
602 void
603 sort_strings (char **array, int nstrings)
604 @{
605 /* @r{Sort @code{temp_array} by comparing the strings.} */
606 qsort (array, sizeof (char *),
607 nstrings, compare_elements);
608 @}
609 @end smallexample
610
611 @cindex converting string to collation order
612 @comment string.h
613 @comment ANSI
614 @deftypefun size_t strxfrm (char *@var{to}, const char *@var{from}, size_t @var{size})
615 The function @code{strxfrm} transforms @var{string} using the collation
616 transformation determined by the locale currently selected for
617 collation, and stores the transformed string in the array @var{to}. Up
618 to @var{size} characters (including a terminating null character) are
619 stored.
620
621 The behavior is undefined if the strings @var{to} and @var{from}
622 overlap; see @ref{Copying and Concatenation}.
623
624 The return value is the length of the entire transformed string. This
625 value is not affected by the value of @var{size}, but if it is greater
626 than @var{size}, it means that the transformed string did not entirely
627 fit in the array @var{to}. In this case, only as much of the string as
628 actually fits was stored. To get the whole transformed string, call
629 @code{strxfrm} again with a bigger output array.
630
631 The transformed string may be longer than the original string, and it
632 may also be shorter.
633
634 If @var{size} is zero, no characters are stored in @var{to}. In this
635 case, @code{strxfrm} simply returns the number of characters that would
636 be the length of the transformed string. This is useful for determining
637 what size string to allocate. It does not matter what @var{to} is if
638 @var{size} is zero; @var{to} may even be a null pointer.
639 @end deftypefun
640
641 Here is an example of how you can use @code{strxfrm} when
642 you plan to do many comparisons. It does the same thing as the previous
643 example, but much faster, because it has to transform each string only
644 once, no matter how many times it is compared with other strings. Even
645 the time needed to allocate and free storage is much less than the time
646 we save, when there are many strings.
647
648 @smallexample
649 struct sorter @{ char *input; char *transformed; @};
650
651 /* @r{This is the comparison function used with @code{qsort}}
652 @r{to sort an array of @code{struct sorter}.} */
653
654 int
655 compare_elements (struct sorter *p1, struct sorter *p2)
656 @{
657 return strcmp (p1->transformed, p2->transformed);
658 @}
659
660 /* @r{This is the entry point---the function to sort}
661 @r{strings using the locale's collating sequence.} */
662
663 void
664 sort_strings_fast (char **array, int nstrings)
665 @{
666 struct sorter temp_array[nstrings];
667 int i;
668
669 /* @r{Set up @code{temp_array}. Each element contains}
670 @r{one input string and its transformed string.} */
671 for (i = 0; i < nstrings; i++)
672 @{
673 size_t length = strlen (array[i]) * 2;
674
675 temp_array[i].input = array[i];
676
677 /* @r{Transform @code{array[i]}.}
678 @r{First try a buffer probably big enough.} */
679 while (1)
680 @{
681 char *transformed = (char *) xmalloc (length);
682 if (strxfrm (transformed, array[i], length) < length)
683 @{
684 temp_array[i].transformed = transformed;
685 break;
686 @}
687 /* @r{Try again with a bigger buffer.} */
688 free (transformed);
689 length *= 2;
690 @}
691 @}
692
693 /* @r{Sort @code{temp_array} by comparing transformed strings.} */
694 qsort (temp_array, sizeof (struct sorter),
695 nstrings, compare_elements);
696
697 /* @r{Put the elements back in the permanent array}
698 @r{in their sorted order.} */
699 for (i = 0; i < nstrings; i++)
700 array[i] = temp_array[i].input;
701
702 /* @r{Free the strings we allocated.} */
703 for (i = 0; i < nstrings; i++)
704 free (temp_array[i].transformed);
705 @}
706 @end smallexample
707
708 @strong{Compatibility Note:} The string collation functions are a new
709 feature of ANSI C. Older C dialects have no equivalent feature.
710
711 @node Search Functions, Finding Tokens in a String, Collation Functions, String and Array Utilities
712 @section Search Functions
713
714 This section describes library functions which perform various kinds
715 of searching operations on strings and arrays. These functions are
716 declared in the header file @file{string.h}.
717 @pindex string.h
718 @cindex search functions (for strings)
719 @cindex string search functions
720
721 @comment string.h
722 @comment ANSI
723 @deftypefun {void *} memchr (const void *@var{block}, int @var{c}, size_t @var{size})
724 This function finds the first occurrence of the byte @var{c} (converted
725 to an @code{unsigned char}) in the initial @var{size} bytes of the
726 object beginning at @var{block}. The return value is a pointer to the
727 located byte, or a null pointer if no match was found.
728 @end deftypefun
729
730 @comment string.h
731 @comment ANSI
732 @deftypefun {char *} strchr (const char *@var{string}, int @var{c})
733 The @code{strchr} function finds the first occurrence of the character
734 @var{c} (converted to a @code{char}) in the null-terminated string
735 beginning at @var{string}. The return value is a pointer to the located
736 character, or a null pointer if no match was found.
737
738 For example,
739 @smallexample
740 strchr ("hello, world", 'l')
741 @result{} "llo, world"
742 strchr ("hello, world", '?')
743 @result{} NULL
744 @end smallexample
745
746 The terminating null character is considered to be part of the string,
747 so you can use this function get a pointer to the end of a string by
748 specifying a null character as the value of the @var{c} argument.
749 @end deftypefun
750
751 @comment string.h
752 @comment BSD
753 @deftypefun {char *} index (const char *@var{string}, int @var{c})
754 @code{index} is another name for @code{strchr}; they are exactly the same.
755 @end deftypefun
756
757 @comment string.h
758 @comment ANSI
759 @deftypefun {char *} strrchr (const char *@var{string}, int @var{c})
760 The function @code{strrchr} is like @code{strchr}, except that it searches
761 backwards from the end of the string @var{string} (instead of forwards
762 from the front).
763
764 For example,
765 @smallexample
766 strrchr ("hello, world", 'l')
767 @result{} "ld"
768 @end smallexample
769 @end deftypefun
770
771 @comment string.h
772 @comment BSD
773 @deftypefun {char *} rindex (const char *@var{string}, int @var{c})
774 @code{rindex} is another name for @code{strrchr}; they are exactly the same.
775 @end deftypefun
776
777 @comment string.h
778 @comment ANSI
779 @deftypefun {char *} strstr (const char *@var{haystack}, const char *@var{needle})
780 This is like @code{strchr}, except that it searches @var{haystack} for a
781 substring @var{needle} rather than just a single character. It
782 returns a pointer into the string @var{haystack} that is the first
783 character of the substring, or a null pointer if no match was found. If
784 @var{needle} is an empty string, the function returns @var{haystack}.
785
786 For example,
787 @smallexample
788 strstr ("hello, world", "l")
789 @result{} "llo, world"
790 strstr ("hello, world", "wo")
791 @result{} "world"
792 @end smallexample
793 @end deftypefun
794
795
796 @comment string.h
797 @comment GNU
798 @deftypefun {void *} memmem (const void *@var{needle}, size_t @var{needle-len},@*const void *@var{haystack}, size_t @var{haystack-len})
799 This is like @code{strstr}, but @var{needle} and @var{haystack} are byte
800 arrays rather than null-terminated strings. @var{needle-len} is the
801 length of @var{needle} and @var{haystack-len} is the length of
802 @var{haystack}.@refill
803
804 This function is a GNU extension.
805 @end deftypefun
806
807 @comment string.h
808 @comment ANSI
809 @deftypefun size_t strspn (const char *@var{string}, const char *@var{skipset})
810 The @code{strspn} (``string span'') function returns the length of the
811 initial substring of @var{string} that consists entirely of characters that
812 are members of the set specified by the string @var{skipset}. The order
813 of the characters in @var{skipset} is not important.
814
815 For example,
816 @smallexample
817 strspn ("hello, world", "abcdefghijklmnopqrstuvwxyz")
818 @result{} 5
819 @end smallexample
820 @end deftypefun
821
822 @comment string.h
823 @comment ANSI
824 @deftypefun size_t strcspn (const char *@var{string}, const char *@var{stopset})
825 The @code{strcspn} (``string complement span'') function returns the length
826 of the initial substring of @var{string} that consists entirely of characters
827 that are @emph{not} members of the set specified by the string @var{stopset}.
828 (In other words, it returns the offset of the first character in @var{string}
829 that is a member of the set @var{stopset}.)
830
831 For example,
832 @smallexample
833 strcspn ("hello, world", " \t\n,.;!?")
834 @result{} 5
835 @end smallexample
836 @end deftypefun
837
838 @comment string.h
839 @comment ANSI
840 @deftypefun {char *} strpbrk (const char *@var{string}, const char *@var{stopset})
841 The @code{strpbrk} (``string pointer break'') function is related to
842 @code{strcspn}, except that it returns a pointer to the first character
843 in @var{string} that is a member of the set @var{stopset} instead of the
844 length of the initial substring. It returns a null pointer if no such
845 character from @var{stopset} is found.
846
847 @c @group Invalid outside the example.
848 For example,
849
850 @smallexample
851 strpbrk ("hello, world", " \t\n,.;!?")
852 @result{} ", world"
853 @end smallexample
854 @c @end group
855 @end deftypefun
856
857 @node Finding Tokens in a String, , Search Functions, String and Array Utilities
858 @section Finding Tokens in a String
859
860 @c !!! Document strsep, which is a better thing to use than strtok.
861
862 @cindex tokenizing strings
863 @cindex breaking a string into tokens
864 @cindex parsing tokens from a string
865 It's fairly common for programs to have a need to do some simple kinds
866 of lexical analysis and parsing, such as splitting a command string up
867 into tokens. You can do this with the @code{strtok} function, declared
868 in the header file @file{string.h}.
869 @pindex string.h
870
871 @comment string.h
872 @comment ANSI
873 @deftypefun {char *} strtok (char *@var{newstring}, const char *@var{delimiters})
874 A string can be split into tokens by making a series of calls to the
875 function @code{strtok}.
876
877 The string to be split up is passed as the @var{newstring} argument on
878 the first call only. The @code{strtok} function uses this to set up
879 some internal state information. Subsequent calls to get additional
880 tokens from the same string are indicated by passing a null pointer as
881 the @var{newstring} argument. Calling @code{strtok} with another
882 non-null @var{newstring} argument reinitializes the state information.
883 It is guaranteed that no other library function ever calls @code{strtok}
884 behind your back (which would mess up this internal state information).
885
886 The @var{delimiters} argument is a string that specifies a set of delimiters
887 that may surround the token being extracted. All the initial characters
888 that are members of this set are discarded. The first character that is
889 @emph{not} a member of this set of delimiters marks the beginning of the
890 next token. The end of the token is found by looking for the next
891 character that is a member of the delimiter set. This character in the
892 original string @var{newstring} is overwritten by a null character, and the
893 pointer to the beginning of the token in @var{newstring} is returned.
894
895 On the next call to @code{strtok}, the searching begins at the next
896 character beyond the one that marked the end of the previous token.
897 Note that the set of delimiters @var{delimiters} do not have to be the
898 same on every call in a series of calls to @code{strtok}.
899
900 If the end of the string @var{newstring} is reached, or if the remainder of
901 string consists only of delimiter characters, @code{strtok} returns
902 a null pointer.
903 @end deftypefun
904
905 @strong{Warning:} Since @code{strtok} alters the string it is parsing,
906 you always copy the string to a temporary buffer before parsing it with
907 @code{strtok}. If you allow @code{strtok} to modify a string that came
908 from another part of your program, you are asking for trouble; that
909 string may be part of a data structure that could be used for other
910 purposes during the parsing, when alteration by @code{strtok} makes the
911 data structure temporarily inaccurate.
912
913 The string that you are operating on might even be a constant. Then
914 when @code{strtok} tries to modify it, your program will get a fatal
915 signal for writing in read-only memory. @xref{Program Error Signals}.
916
917 This is a special case of a general principle: if a part of a program
918 does not have as its purpose the modification of a certain data
919 structure, then it is error-prone to modify the data structure
920 temporarily.
921
922 The function @code{strtok} is not reentrant. @xref{Nonreentrancy}, for
923 a discussion of where and why reentrancy is important.
924
925 Here is a simple example showing the use of @code{strtok}.
926
927 @comment Yes, this example has been tested.
928 @smallexample
929 #include <string.h>
930 #include <stddef.h>
931
932 @dots{}
933
934 char string[] = "words separated by spaces -- and, punctuation!";
935 const char delimiters[] = " .,;:!-";
936 char *token;
937
938 @dots{}
939
940 token = strtok (string, delimiters); /* token => "words" */
941 token = strtok (NULL, delimiters); /* token => "separated" */
942 token = strtok (NULL, delimiters); /* token => "by" */
943 token = strtok (NULL, delimiters); /* token => "spaces" */
944 token = strtok (NULL, delimiters); /* token => "and" */
945 token = strtok (NULL, delimiters); /* token => "punctuation" */
946 token = strtok (NULL, delimiters); /* token => NULL */
947 @end smallexample