1 @node String and Array Utilities, Extended Characters, Character Handling, Top
2 @chapter String and Array Utilities
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.
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.
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
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
29 * String/Array Comparison:: Functions for byte-wise and character-wise
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
37 @node Representation of Strings, String/Array Conventions, , String and Array Utilities
38 @section Representation of Strings
39 @cindex string, representation of
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.
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.
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'}.
63 A null character is quite different conceptually from a null pointer,
64 although both are represented by the integer @code{0}.
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.
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
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
91 @cindex string allocation
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
102 @c !!! I think the / looks bad in the printed manual---use `and' instead? -rm
103 @node String/Array Conventions, String Length, Representation of Strings, String and Array Utilities
104 @section String/Array Conventions
106 This chapter describes both functions that work on arbitrary arrays or
107 blocks of memory, and functions that are specific to null-terminated
108 arrays of characters.
110 Functions that operate on arbitrary blocks of memory have names
111 beginning with @samp{mem} (such as @code{memcpy}) and invariably take an
112 argument which specifies the size (in bytes) of the block of memory to
113 operate on. The array arguments and return values for these functions
114 have type @code{void *}, and as a matter of style, the elements of these
115 arrays are referred to as ``bytes''. You can pass any kind of pointer
116 to these functions, and the @code{sizeof} operator is useful in
117 computing the value for the size argument.
119 In contrast, functions that operate specifically on strings have names
120 beginning with @samp{str} (such as @code{strcpy}) and look for a null
121 character to terminate the string instead of requiring an explicit size
122 argument to be passed. (Some of these functions accept a specified
123 maximum length, but they also check for premature termination with a
124 null character.) The array arguments and return values for these
125 functions have type @code{char *}, and the array elements are referred
126 to as ``characters''.
128 In many cases, there are both @samp{mem} and @samp{str} versions of a
129 function. The one that is more appropriate to use depends on the exact
130 situation. When your program is manipulating arbitrary arrays or blocks of
131 storage, then you should always use the @samp{mem} functions. On the
132 other hand, when you are manipulating null-terminated strings it is
133 usually more convenient to use the @samp{str} functions, unless you
134 already know the length of the string in advance.
136 @node String Length, Copying and Concatenation, String/Array Conventions, String and Array Utilities
137 @section String Length
139 You can get the length of a string using the @code{strlen} function.
140 This function is declared in the header file @file{string.h}.
145 @deftypefun size_t strlen (const char *@var{s})
146 The @code{strlen} function returns the length of the null-terminated
147 string @var{s}. (In other words, it returns the offset of the terminating
148 null character within the array.)
152 strlen ("hello, world")
156 When applied to a character array, the @code{strlen} function returns
157 the length of the string stored there, not its allocation size. You can
158 get the allocation size of the character array that holds a string using
159 the @code{sizeof} operator:
162 char string[32] = "hello, world";
170 @node Copying and Concatenation, String/Array Comparison, String Length, String and Array Utilities
171 @section Copying and Concatenation
173 You can use the functions described in this section to copy the contents
174 of strings and arrays, or to append the contents of one string to
175 another. These functions are declared in the header file
178 @cindex copying strings and arrays
179 @cindex string copy functions
180 @cindex array copy functions
181 @cindex concatenating strings
182 @cindex string concatenation functions
184 A helpful way to remember the ordering of the arguments to the functions
185 in this section is that it corresponds to an assignment expression, with
186 the destination array specified to the left of the source array. All
187 of these functions return the address of the destination array.
189 Most of these functions do not work properly if the source and
190 destination arrays overlap. For example, if the beginning of the
191 destination array overlaps the end of the source array, the original
192 contents of that part of the source array may get overwritten before it
193 is copied. Even worse, in the case of the string functions, the null
194 character marking the end of the string may be lost, and the copy
195 function might get stuck in a loop trashing all the memory allocated to
198 All functions that have problems copying between overlapping arrays are
199 explicitly identified in this manual. In addition to functions in this
200 section, there are a few others like @code{sprintf} (@pxref{Formatted
201 Output Functions}) and @code{scanf} (@pxref{Formatted Input
206 @deftypefun {void *} memcpy (void *@var{to}, const void *@var{from}, size_t @var{size})
207 The @code{memcpy} function copies @var{size} bytes from the object
208 beginning at @var{from} into the object beginning at @var{to}. The
209 behavior of this function is undefined if the two arrays @var{to} and
210 @var{from} overlap; use @code{memmove} instead if overlapping is possible.
212 The value returned by @code{memcpy} is the value of @var{to}.
214 Here is an example of how you might use @code{memcpy} to copy the
215 contents of a @code{struct}:
218 struct foo *old, *new;
220 memcpy (new, old, sizeof(struct foo));
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}.
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}.
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}.
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}.
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}.
267 If the length of @var{from} is more than @var{size}, then @code{strncpy}
268 copies just the first @var{size} characters.
270 If the length of @var{from} is less than @var{size}, then @code{strncpy}
271 copies all of @var{from}, followed by enough null characters to add up
272 to @var{size} characters in all. This behavior is rarely useful, but it
273 is specified by the ANSI C standard.
275 The behavior of @code{strncpy} is undefined if the strings overlap.
277 Using @code{strncpy} as opposed to @code{strcpy} is a way to avoid bugs
278 relating to writing past the end of the allocated space for @var{to}.
279 However, it can also make your program much slower in one common case:
280 copying a string which is probably small into a potentially large buffer.
281 In this case, @var{size} may be large, and when it is, @code{strncpy} will
282 waste a considerable amount of time copying null characters.
287 @deftypefun {char *} strdup (const char *@var{s})
288 This function copies the null-terminated string @var{s} into a newly
289 allocated string. The string is allocated using @code{malloc}; see
290 @ref{Unconstrained Allocation}. If @code{malloc} cannot allocate space
291 for the new string, @code{strdup} returns a null pointer. Otherwise it
292 returns a pointer to the new string.
296 @comment Unknown origin
297 @deftypefun {char *} stpcpy (char *@var{to}, const char *@var{from})
298 This function is like @code{strcpy}, except that it returns a pointer to
299 the end of the string @var{to} (that is, the address of the terminating
300 null character) rather than the beginning.
302 For example, this program uses @code{stpcpy} to concatenate @samp{foo}
303 and @samp{bar} to produce @samp{foobar}, which it then prints.
306 @include stpcpy.c.texi
309 This function is not part of the ANSI or POSIX standards, and is not
310 customary on Unix systems, but we did not invent it either. Perhaps it
313 Its behavior is undefined if the strings overlap.
318 @deftypefun {char *} strcat (char *@var{to}, const char *@var{from})
319 The @code{strcat} function is similar to @code{strcpy}, except that the
320 characters from @var{from} are concatenated or appended to the end of
321 @var{to}, instead of overwriting it. That is, the first character from
322 @var{from} overwrites the null character marking the end of @var{to}.
324 An equivalent definition for @code{strcat} would be:
328 strcat (char *to, const char *from)
330 strcpy (to + strlen (to), from);
335 This function has undefined results if the strings overlap.
340 @deftypefun {char *} strncat (char *@var{to}, const char *@var{from}, size_t @var{size})
341 This function is like @code{strcat} except that not more than @var{size}
342 characters from @var{from} are appended to the end of @var{to}. A
343 single null character is also always appended to @var{to}, so the total
344 allocated size of @var{to} must be at least @code{@var{size} + 1} bytes
345 longer than its initial length.
347 @c !!! why is this here? It should be introduced.
351 strncat (char *to, const char *from, size_t size)
353 strncpy (to + strlen (to), from, size);
359 The behavior of @code{strncat} is undefined if the strings overlap.
362 Here is an example showing the use of @code{strncpy} and @code{strncat}.
363 Notice how, in the call to @code{strncat}, the @var{size} parameter
364 is computed to avoid overflowing the character array @code{buffer}.
367 @include strncat.c.texi
371 The output produced by this program looks like:
380 @deftypefun {void *} bcopy (void *@var{from}, const void *@var{to}, size_t @var{size})
381 This is a partially obsolete alternative for @code{memmove}, derived from
382 BSD. Note that it is not quite equivalent to @code{memmove}, because the
383 arguments are not in the same order.
388 @deftypefun {void *} bzero (void *@var{block}, size_t @var{size})
389 This is a partially obsolete alternative for @code{memset}, derived from
390 BSD. Note that it is not as general as @code{bmemset}, because the only
391 value it can store is zero.
394 @node String/Array Comparison, Collation Functions, Copying and Concatenation, String and Array Utilities
395 @section String/Array Comparison
396 @cindex comparing strings and arrays
397 @cindex string comparison functions
398 @cindex array comparison functions
399 @cindex predicates on strings
400 @cindex predicates on arrays
402 You can use the functions in this section to perform comparisons on the
403 contents of strings and arrays. As well as checking for equality, these
404 functions can also be used as the ordering functions for sorting
405 operations. @xref{Searching and Sorting}, for an example of this.
407 Unlike most comparison operations in C, the string comparison functions
408 return a nonzero value if the strings are @emph{not} equivalent rather
409 than if they are. The sign of the value indicates the relative ordering
410 of the first characters in the strings that are not equivalent: a
411 negative value indicates that the first string is ``less'' than the
412 second, while a positive value indicates that the first string is
415 If you are using these functions only to check for equality, you might
416 find it makes for a cleaner program to hide them behind a macro
417 definition, like this:
420 #define str_eq(s1,s2) (!strcmp ((s1),(s2)))
423 All of these functions are declared in the header file @file{string.h}.
428 @deftypefun int memcmp (const void *@var{a1}, const void *@var{a2}, size_t @var{size})
429 The function @code{memcmp} compares the @var{size} bytes of memory
430 beginning at @var{a1} against the @var{size} bytes of memory beginning
431 at @var{a2}. The value returned has the same sign as the difference
432 between the first differing pair of bytes (interpreted as @code{unsigned
433 char} objects, then promoted to @code{int}).
435 If the contents of the two blocks are equal, @code{memcmp} returns
439 On arbitrary arrays, the @code{memcmp} function is mostly useful for
440 testing equality. It usually isn't meaningful to do byte-wise ordering
441 comparisons on arrays of things other than bytes. For example, a
442 byte-wise comparison on the bytes that make up floating-point numbers
443 isn't likely to tell you anything about the relationship between the
444 values of the floating-point numbers.
446 You should also be careful about using @code{memcmp} to compare objects
447 that can contain ``holes'', such as the padding inserted into structure
448 objects to enforce alignment requirements, extra space at the end of
449 unions, and extra characters at the ends of strings whose length is less
450 than their allocated size. The contents of these ``holes'' are
451 indeterminate and may cause strange behavior when performing byte-wise
452 comparisons. For more predictable results, perform an explicit
453 component-wise comparison.
455 For example, given a structure type definition like:
471 you are better off writing a specialized comparison function to compare
472 @code{struct foo} objects instead of comparing them with @code{memcmp}.
476 @deftypefun int strcmp (const char *@var{s1}, const char *@var{s2})
477 The @code{strcmp} function compares the string @var{s1} against
478 @var{s2}, returning a value that has the same sign as the difference
479 between the first differing pair of characters (interpreted as
480 @code{unsigned char} objects, then promoted to @code{int}).
482 If the two strings are equal, @code{strcmp} returns @code{0}.
484 A consequence of the ordering used by @code{strcmp} is that if @var{s1}
485 is an initial substring of @var{s2}, then @var{s1} is considered to be
486 ``less than'' @var{s2}.
491 @deftypefun int strcasecmp (const char *@var{s1}, const char *@var{s2})
492 This function is like @code{strcmp}, except that differences in case
495 @code{strcasecmp} is derived from BSD.
500 @deftypefun int strncasecmp (const char *@var{s1}, const char *@var{s2}, size_t @var{n})
501 This function is like @code{strncmp}, except that differences in case
504 @code{strncasecmp} is a GNU extension.
509 @deftypefun int strncmp (const char *@var{s1}, const char *@var{s2}, size_t @var{size})
510 This function is the similar to @code{strcmp}, except that no more than
511 @var{size} characters are compared. In other words, if the two strings are
512 the same in their first @var{size} characters, the return value is zero.
515 Here are some examples showing the use of @code{strcmp} and @code{strncmp}.
516 These examples assume the use of the ASCII character set. (If some
517 other character set---say, EBCDIC---is used instead, then the glyphs
518 are associated with different numeric codes, and the return values
519 and ordering may differ.)
522 strcmp ("hello", "hello")
523 @result{} 0 /* @r{These two strings are the same.} */
524 strcmp ("hello", "Hello")
525 @result{} 32 /* @r{Comparisons are case-sensitive.} */
526 strcmp ("hello", "world")
527 @result{} -15 /* @r{The character @code{'h'} comes before @code{'w'}.} */
528 strcmp ("hello", "hello, world")
529 @result{} -44 /* @r{Comparing a null character against a comma.} */
530 strncmp ("hello", "hello, world"", 5)
531 @result{} 0 /* @r{The initial 5 characters are the same.} */
532 strncmp ("hello, world", "hello, stupid world!!!", 5)
533 @result{} 0 /* @r{The initial 5 characters are the same.} */
538 @deftypefun int bcmp (const void *@var{a1}, const void *@var{a2}, size_t @var{size})
539 This is an obsolete alias for @code{memcmp}, derived from BSD.
542 @node Collation Functions, Search Functions, String/Array Comparison, String and Array Utilities
543 @section Collation Functions
545 @cindex collating strings
546 @cindex string collation functions
548 In some locales, the conventions for lexicographic ordering differ from
549 the strict numeric ordering of character codes. For example, in Spanish
550 most glyphs with diacritical marks such as accents are not considered
551 distinct letters for the purposes of collation. On the other hand, the
552 two-character sequence @samp{ll} is treated as a single letter that is
553 collated immediately after @samp{l}.
555 You can use the functions @code{strcoll} and @code{strxfrm} (declared in
556 the header file @file{string.h}) to compare strings using a collation
557 ordering appropriate for the current locale. The locale used by these
558 functions in particular can be specified by setting the locale for the
559 @code{LC_COLLATE} category; see @ref{Locales}.
562 In the standard C locale, the collation sequence for @code{strcoll} is
563 the same as that for @code{strcmp}.
565 Effectively, the way these functions work is by applying a mapping to
566 transform the characters in a string to a byte sequence that represents
567 the string's position in the collating sequence of the current locale.
568 Comparing two such byte sequences in a simple fashion is equivalent to
569 comparing the strings with the locale's collating sequence.
571 The function @code{strcoll} performs this translation implicitly, in
572 order to do one comparison. By contrast, @code{strxfrm} performs the
573 mapping explicitly. If you are making multiple comparisons using the
574 same string or set of strings, it is likely to be more efficient to use
575 @code{strxfrm} to transform all the strings just once, and subsequently
576 compare the transformed strings with @code{strcmp}.
580 @deftypefun int strcoll (const char *@var{s1}, const char *@var{s2})
581 The @code{strcoll} function is similar to @code{strcmp} but uses the
582 collating sequence of the current locale for collation (the
583 @code{LC_COLLATE} locale).
586 Here is an example of sorting an array of strings, using @code{strcoll}
587 to compare them. The actual sort algorithm is not written here; it
588 comes from @code{qsort} (@pxref{Array Sort Function}). The job of the
589 code shown here is to say how to compare the strings while sorting them.
590 (Later on in this section, we will show a way to do this more
591 efficiently using @code{strxfrm}.)
594 /* @r{This is the comparison function used with @code{qsort}.} */
597 compare_elements (char **p1, char **p2)
599 return strcoll (*p1, *p2);
602 /* @r{This is the entry point---the function to sort}
603 @r{strings using the locale's collating sequence.} */
606 sort_strings (char **array, int nstrings)
608 /* @r{Sort @code{temp_array} by comparing the strings.} */
609 qsort (array, sizeof (char *),
610 nstrings, compare_elements);
614 @cindex converting string to collation order
617 @deftypefun size_t strxfrm (char *@var{to}, const char *@var{from}, size_t @var{size})
618 The function @code{strxfrm} transforms @var{string} using the collation
619 transformation determined by the locale currently selected for
620 collation, and stores the transformed string in the array @var{to}. Up
621 to @var{size} characters (including a terminating null character) are
624 The behavior is undefined if the strings @var{to} and @var{from}
625 overlap; see @ref{Copying and Concatenation}.
627 The return value is the length of the entire transformed string. This
628 value is not affected by the value of @var{size}, but if it is greater
629 than @var{size}, it means that the transformed string did not entirely
630 fit in the array @var{to}. In this case, only as much of the string as
631 actually fits was stored. To get the whole transformed string, call
632 @code{strxfrm} again with a bigger output array.
634 The transformed string may be longer than the original string, and it
637 If @var{size} is zero, no characters are stored in @var{to}. In this
638 case, @code{strxfrm} simply returns the number of characters that would
639 be the length of the transformed string. This is useful for determining
640 what size string to allocate. It does not matter what @var{to} is if
641 @var{size} is zero; @var{to} may even be a null pointer.
644 Here is an example of how you can use @code{strxfrm} when
645 you plan to do many comparisons. It does the same thing as the previous
646 example, but much faster, because it has to transform each string only
647 once, no matter how many times it is compared with other strings. Even
648 the time needed to allocate and free storage is much less than the time
649 we save, when there are many strings.
652 struct sorter @{ char *input; char *transformed; @};
654 /* @r{This is the comparison function used with @code{qsort}}
655 @r{to sort an array of @code{struct sorter}.} */
658 compare_elements (struct sorter *p1, struct sorter *p2)
660 return strcmp (p1->transformed, p2->transformed);
663 /* @r{This is the entry point---the function to sort}
664 @r{strings using the locale's collating sequence.} */
667 sort_strings_fast (char **array, int nstrings)
669 struct sorter temp_array[nstrings];
672 /* @r{Set up @code{temp_array}. Each element contains}
673 @r{one input string and its transformed string.} */
674 for (i = 0; i < nstrings; i++)
676 size_t length = strlen (array[i]) * 2;
678 temp_array[i].input = array[i];
680 /* @r{Transform @code{array[i]}.}
681 @r{First try a buffer probably big enough.} */
684 char *transformed = (char *) xmalloc (length);
685 if (strxfrm (transformed, array[i], length) < length)
687 temp_array[i].transformed = transformed;
690 /* @r{Try again with a bigger buffer.} */
696 /* @r{Sort @code{temp_array} by comparing transformed strings.} */
697 qsort (temp_array, sizeof (struct sorter),
698 nstrings, compare_elements);
700 /* @r{Put the elements back in the permanent array}
701 @r{in their sorted order.} */
702 for (i = 0; i < nstrings; i++)
703 array[i] = temp_array[i].input;
705 /* @r{Free the strings we allocated.} */
706 for (i = 0; i < nstrings; i++)
707 free (temp_array[i].transformed);
711 @strong{Compatibility Note:} The string collation functions are a new
712 feature of ANSI C. Older C dialects have no equivalent feature.
714 @node Search Functions, Finding Tokens in a String, Collation Functions, String and Array Utilities
715 @section Search Functions
717 This section describes library functions which perform various kinds
718 of searching operations on strings and arrays. These functions are
719 declared in the header file @file{string.h}.
721 @cindex search functions (for strings)
722 @cindex string search functions
726 @deftypefun {void *} memchr (const void *@var{block}, int @var{c}, size_t @var{size})
727 This function finds the first occurrence of the byte @var{c} (converted
728 to an @code{unsigned char}) in the initial @var{size} bytes of the
729 object beginning at @var{block}. The return value is a pointer to the
730 located byte, or a null pointer if no match was found.
735 @deftypefun {char *} strchr (const char *@var{string}, int @var{c})
736 The @code{strchr} function finds the first occurrence of the character
737 @var{c} (converted to a @code{char}) in the null-terminated string
738 beginning at @var{string}. The return value is a pointer to the located
739 character, or a null pointer if no match was found.
743 strchr ("hello, world", 'l')
744 @result{} "llo, world"
745 strchr ("hello, world", '?')
749 The terminating null character is considered to be part of the string,
750 so you can use this function get a pointer to the end of a string by
751 specifying a null character as the value of the @var{c} argument.
756 @deftypefun {char *} strrchr (const char *@var{string}, int @var{c})
757 The function @code{strrchr} is like @code{strchr}, except that it searches
758 backwards from the end of the string @var{string} (instead of forwards
763 strrchr ("hello, world", 'l')
770 @deftypefun {char *} strstr (const char *@var{haystack}, const char *@var{needle})
771 This is like @code{strchr}, except that it searches @var{needle} for a
772 substring @var{haystack} rather than just a single character. It
773 returns a pointer into the string @var{needle} that is the first
774 character of the substring, or a null pointer if no match was found. If
775 @var{haystack} is an empty string, the function returns @var{needle}.
779 strstr ("hello, world", "l")
780 @result{} "llo, world"
781 strstr ("hello, world", "wo")
789 @deftypefun {void *} memmem (const void *@var{needle}, size_t @var{needle_len},@*const void *@var{haystack}, size_t @var{haystack_len})
790 This is like @code{strstr}, but @var{needle} and @var{haystack} are byte
791 arrays rather than null-terminated strings. @var{needle_len} is the
792 length of @var{needle} and @var{haystack_len} is the length of
793 @var{haystack}.@refill
795 This function is a GNU extension.
800 @deftypefun size_t strspn (const char *@var{string}, const char *@var{skipset})
801 The @code{strspn} (``string span'') function returns the length of the
802 initial substring of @var{string} that consists entirely of characters that
803 are members of the set specified by the string @var{skipset}. The order
804 of the characters in @var{skipset} is not important.
808 strspn ("hello, world", "abcdefghijklmnopqrstuvwxyz")
815 @deftypefun size_t strcspn (const char *@var{string}, const char *@var{stopset})
816 The @code{strcspn} (``string complement span'') function returns the length
817 of the initial substring of @var{string} that consists entirely of characters
818 that are @emph{not} members of the set specified by the string @var{stopset}.
819 (In other words, it returns the offset of the first character in @var{string}
820 that is a member of the set @var{stopset}.)
824 strcspn ("hello, world", " \t\n,.;!?")
831 @deftypefun {char *} strpbrk (const char *@var{string}, const char *@var{stopset})
832 The @code{strpbrk} (``string pointer break'') function is related to
833 @code{strcspn}, except that it returns a pointer to the first character
834 in @var{string} that is a member of the set @var{stopset} instead of the
835 length of the initial substring. It returns a null pointer if no such
836 character from @var{stopset} is found.
838 @c @group Invalid outside the example.
842 strpbrk ("hello, world", " \t\n,.;!?")
848 @node Finding Tokens in a String, , Search Functions, String and Array Utilities
849 @section Finding Tokens in a String
851 @c !!! Document strsep, which is a better thing to use than strtok.
853 @cindex tokenizing strings
854 @cindex breaking a string into tokens
855 @cindex parsing tokens from a string
856 It's fairly common for programs to have a need to do some simple kinds
857 of lexical analysis and parsing, such as splitting a command string up
858 into tokens. You can do this with the @code{strtok} function, declared
859 in the header file @file{string.h}.
864 @deftypefun {char *} strtok (char *@var{newstring}, const char *@var{delimiters})
865 A string can be split into tokens by making a series of calls to the
866 function @code{strtok}.
868 The string to be split up is passed as the @var{newstring} argument on
869 the first call only. The @code{strtok} function uses this to set up
870 some internal state information. Subsequent calls to get additional
871 tokens from the same string are indicated by passing a null pointer as
872 the @var{newstring} argument. Calling @code{strtok} with another
873 non-null @var{newstring} argument reinitializes the state information.
874 It is guaranteed that no other library function ever calls @code{strtok}
875 behind your back (which would mess up this internal state information).
877 The @var{delimiters} argument is a string that specifies a set of delimiters
878 that may surround the token being extracted. All the initial characters
879 that are members of this set are discarded. The first character that is
880 @emph{not} a member of this set of delimiters marks the beginning of the
881 next token. The end of the token is found by looking for the next
882 character that is a member of the delimiter set. This character in the
883 original string @var{newstring} is overwritten by a null character, and the
884 pointer to the beginning of the token in @var{newstring} is returned.
886 On the next call to @code{strtok}, the searching begins at the next
887 character beyond the one that marked the end of the previous token.
888 Note that the set of delimiters @var{delimiters} do not have to be the
889 same on every call in a series of calls to @code{strtok}.
891 If the end of the string @var{newstring} is reached, or if the remainder of
892 string consists only of delimiter characters, @code{strtok} returns
896 @strong{Warning:} Since @code{strtok} alters the string it is parsing,
897 you always copy the string to a temporary buffer before parsing it with
898 @code{strtok}. If you allow @code{strtok} to modify a string that came
899 from another part of your program, you are asking for trouble; that
900 string may be part of a data structure that could be used for other
901 purposes during the parsing, when alteration by @code{strtok} makes the
902 data structure temporarily inaccurate.
904 The string that you are operating on might even be a constant. Then
905 when @code{strtok} tries to modify it, your program will get a fatal
906 signal for writing in read-only memory. @xref{Program Error Signals}.
908 This is a special case of a general principle: if a part of a program
909 does not have as its purpose the modification of a certain data
910 structure, then it is error-prone to modify the data structure
913 The function @code{strtok} is not reentrant. @xref{Nonreentrancy}, for
914 a discussion of where and why reentrancy is important.
916 Here is a simple example showing the use of @code{strtok}.
918 @comment Yes, this example has been tested.
925 char string[] = "words separated by spaces -- and, punctuation!";
926 const char delimiters[] = " .,;:!-";
931 token = strtok (string, delimiters); /* token => "words" */
932 token = strtok (NULL, delimiters); /* token => "separated" */
933 token = strtok (NULL, delimiters); /* token => "by" */
934 token = strtok (NULL, delimiters); /* token => "spaces" */
935 token = strtok (NULL, delimiters); /* token => "and" */
936 token = strtok (NULL, delimiters); /* token => "punctuation" */
937 token = strtok (NULL, delimiters); /* token => NULL */