Everything

strtok


Divides a specified string into some tokens.

[Format]

#include <string.h>

char *strtok (char *s1, const char *s2);

[Return values]

If division into tokens is successful: Pointer to the first token divided

If division into tokens is unsuccessful: NULL

[Parameters]

s1 Pointer to the string to be divided into some tokens

s2 Pointer to the string representing string-dividing characters

[Remarks]

The strtok function should be repeatedly called to divide a string.

(a)

First call

The string pointed by s1 is divided at a character included in the string pointed by s2. If a token has been separated, the function returns a pointer to the beginning of that token. Otherwise, the function returns NULL.

(b)

Second and subsequent calls

Starting from the next character separated before as the token, the function repeats division at a character included in the string pointed by s2. If a token has been separated, the function returns a pointer to the beginning of that token. Otherwise, the function returns NULL.

At the second and subsequent calls, specify NULL as the first parameter. The string pointed by s2 can be changed at each call. The null character is appended at the end of a separated token.

An example of use of the strtok function is shown below.

Example

          1  #include <string.h>
          2  static char s1[ ]="a@b, @c/@d";
          3  char *ret;
          4
          5  ret = strtok(s1, "@");
          6  ret = strtok(NULL, ",@");
          7  ret = strtok(NULL, "/@");
          8  ret = strtok(NULL, "@");

Explanation:

The above example program uses the strtok function to divide string "a@b, @c/@d" into tokens a, b, c, and d.

The second line specifies string "a@b, @c/@d" as an initial value for string s1.

The fifth line calls the strtok function to divide tokens using '@' as the delimiter. As a result, a pointer to character 'a' is returned, and the null character is embedded at '@,' the first delimiter after character 'a.' Thus string 'a' has been separated.

Specify NULL for the first parameter to consecutively separate tokens from the same string, and repeat calling the strtok function.

Consequently, the function separates strings 'b,' 'c,' and 'd.'