#include <string.h>char *strtok(char *str1, const char *str2);

The strtok( ) function returns a pointer to the next token in the string pointed to by str1. The characters making up the string pointed to by str2 are the delimiters that determine the token. A null pointer is returned when there is no token to return.

In C99, str1 and str2 are qualified by restrict.

To tokenize a string, the first call to strtok( ) must have str1 point to the string being tokenized. Subsequent calls must use a null pointer for str1. In this way, the entire string can be reduced to its tokens.

It is possible to use a different set of delimiters for each call to strtok( ).

Related functions are strchr( ), strcspn( ), strpbrk( ), strrchr( ), and strspn( ).

Programming Tip 

The strtok( ) function provides a means by which you can reduce a string to its constituent parts. For example, the following program tokenizes the string “One, two, and three.”

#include <stdio.h>  #include <string.h>    int main(void)  {    char *p;    char str[] = "One, two, and three.";     p = strtok(str, ",");    printf(p);    do {      p = strtok(NULL, ",. ");      if(p) printf("|%s", p);    } while(p);      return 0;  }

The output produced by this program is


Notice how strtok( ) is first called with a pointer to the string to be tokenized, but subsequent calls use NULL for the first argument. The strtok( ) function maintains an internal pointer into the string being tokenized. When strtok( )'s first argument points to a string, this internal pointer is reset to point to that string. When the first argument is NULL, strtok( ) continues tokenizing the previous string from the point at which it left off, advancing the internal pointer as each token is obtained. This way, strtok( ) can tokenize an entire string. Also notice how the string that defines the delimiters was changed between the first call and the subsequent calls. Each call can define the delimiters differently.

C(s)C++ Programmer's Reference
C Programming on the IBM PC (C Programmers Reference Guide Series)
ISBN: 0673462897
EAN: 2147483647
Year: 2002
Pages: 539 © 2008-2017.
If you may any questions please contact us: