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 @node String/Array Conventions, String Length, Representation of Strings, String and Array Utilities
103 @section String and Array Conventions
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.
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.
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''.
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.
135 @node String Length, Copying and Concatenation, String/Array Conventions, String and Array Utilities
136 @section String Length
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}.
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.)
151 strlen ("hello, world")
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:
161 char string[32] = "hello, world";
169 @node Copying and Concatenation, String/Array Comparison, String Length, String and Array Utilities
170 @section Copying and Concatenation
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
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
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.
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
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
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.
211 The value returned by @code{memcpy} is the value of @var{to}.
213 Here is an example of how you might use @code{memcpy} to copy the
214 contents of an array:
217 struct foo *oldarray, *newarray;
220 memcpy (new, old, arraysize * 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. Note that in this case
269 there is no null terminator written into @var{to}.
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.
276 The behavior of @code{strncpy} is undefined if the strings overlap.
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.
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.
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.
303 For example, this program uses @code{stpcpy} to concatenate @samp{foo}
304 and @samp{bar} to produce @samp{foobar}, which it then prints.
307 @include stpcpy.c.texi
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
314 Its behavior is undefined if the strings overlap.
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}.
325 An equivalent definition for @code{strcat} would be:
329 strcat (char *to, const char *from)
331 strcpy (to + strlen (to), from);
336 This function has undefined results if the strings overlap.
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.
348 The @code{strncat} function could be implemented like this:
353 strncat (char *to, const char *from, size_t size)
355 strncpy (to + strlen (to), from, size);
361 The behavior of @code{strncat} is undefined if the strings overlap.
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}.
369 @include strncat.c.texi
373 The output produced by this program looks like:
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.
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.
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
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.
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
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)}}.
420 All of these functions are declared in the header file @file{string.h}.
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}).
432 If the contents of the two blocks are equal, @code{memcmp} returns
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.
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.
452 For example, given a structure type definition like:
468 you are better off writing a specialized comparison function to compare
469 @code{struct foo} objects instead of comparing them with @code{memcmp}.
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}).
479 If the two strings are equal, @code{strcmp} returns @code{0}.
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}.
488 @deftypefun int strcasecmp (const char *@var{s1}, const char *@var{s2})
489 This function is like @code{strcmp}, except that differences in case
492 @code{strcasecmp} is derived from 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
501 @code{strncasecmp} is a GNU extension.
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.
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.)
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.} */
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.
539 @node Collation Functions, Search Functions, String/Array Comparison, String and Array Utilities
540 @section Collation Functions
542 @cindex collating strings
543 @cindex string collation functions
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}.
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}.
559 In the standard C locale, the collation sequence for @code{strcoll} is
560 the same as that for @code{strcmp}.
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.
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}.
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).
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}.)
591 /* @r{This is the comparison function used with @code{qsort}.} */
594 compare_elements (char **p1, char **p2)
596 return strcoll (*p1, *p2);
599 /* @r{This is the entry point---the function to sort}
600 @r{strings using the locale's collating sequence.} */
603 sort_strings (char **array, int nstrings)
605 /* @r{Sort @code{temp_array} by comparing the strings.} */
606 qsort (array, sizeof (char *),
607 nstrings, compare_elements);
611 @cindex converting string to collation order
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
621 The behavior is undefined if the strings @var{to} and @var{from}
622 overlap; see @ref{Copying and Concatenation}.
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.
631 The transformed string may be longer than the original string, and it
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.
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.
649 struct sorter @{ char *input; char *transformed; @};
651 /* @r{This is the comparison function used with @code{qsort}}
652 @r{to sort an array of @code{struct sorter}.} */
655 compare_elements (struct sorter *p1, struct sorter *p2)
657 return strcmp (p1->transformed, p2->transformed);
660 /* @r{This is the entry point---the function to sort}
661 @r{strings using the locale's collating sequence.} */
664 sort_strings_fast (char **array, int nstrings)
666 struct sorter temp_array[nstrings];
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++)
673 size_t length = strlen (array[i]) * 2;
675 temp_array[i].input = array[i];
677 /* @r{Transform @code{array[i]}.}
678 @r{First try a buffer probably big enough.} */
681 char *transformed = (char *) xmalloc (length);
682 if (strxfrm (transformed, array[i], length) < length)
684 temp_array[i].transformed = transformed;
687 /* @r{Try again with a bigger buffer.} */
693 /* @r{Sort @code{temp_array} by comparing transformed strings.} */
694 qsort (temp_array, sizeof (struct sorter),
695 nstrings, compare_elements);
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;
702 /* @r{Free the strings we allocated.} */
703 for (i = 0; i < nstrings; i++)
704 free (temp_array[i].transformed);
708 @strong{Compatibility Note:} The string collation functions are a new
709 feature of ANSI C. Older C dialects have no equivalent feature.
711 @node Search Functions, Finding Tokens in a String, Collation Functions, String and Array Utilities
712 @section Search Functions
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}.
718 @cindex search functions (for strings)
719 @cindex string search functions
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.
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.
740 strchr ("hello, world", 'l')
741 @result{} "llo, world"
742 strchr ("hello, world", '?')
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.
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.
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
766 strrchr ("hello, world", 'l')
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.
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}.
788 strstr ("hello, world", "l")
789 @result{} "llo, world"
790 strstr ("hello, world", "wo")
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
804 This function is a GNU extension.
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.
817 strspn ("hello, world", "abcdefghijklmnopqrstuvwxyz")
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}.)
833 strcspn ("hello, world", " \t\n,.;!?")
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.
847 @c @group Invalid outside the example.
851 strpbrk ("hello, world", " \t\n,.;!?")
857 @node Finding Tokens in a String, , Search Functions, String and Array Utilities
858 @section Finding Tokens in a String
860 @c !!! Document strsep, which is a better thing to use than strtok.
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}.
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}.
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).
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.
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}.
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
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.
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}.
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
922 The function @code{strtok} is not reentrant. @xref{Nonreentrancy}, for
923 a discussion of where and why reentrancy is important.
925 Here is a simple example showing the use of @code{strtok}.
927 @comment Yes, this example has been tested.
934 char string[] = "words separated by spaces -- and, punctuation!";
935 const char delimiters[] = " .,;:!-";
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 */