Locates text tokens in a given string. The text tokens are delimited by one or more characters from a separator string that you specify. This function keeps track of its position in the string between calls and, as successive calls are made, the function works through the string, identifying the text token following the one identified by the previous call.
#include <string.h> char *strtok (char *s1, const char *s2);Function Variants This function also has variants named _strtok32 and _strtok64 for use with 32-bit and 64-bit pointer sizes, respectively. See Section 1.8 for more information on using pointer-size-specific functions.
The first call to the strtok function returns a pointer to the first character in the first token and writes a null character into s1 immediately following the returned token. Each subsequent call (with the value of the first argument remaining NULL) returns a pointer to a subsequent token in the string originally pointed to by s1. When no tokens remain in the string, the strtok function returns a NULL pointer. (This can occur on the first call to strtok if the string is empty or contains only separator characters.)
Since strtok inserts null characters into s1 to delimit tokens, s1 cannot be a const object.
x | A pointer to the first character of a token. |
NULL | Indicates that there are no tokens remaining in s1. |
#include <stdio.h> #include <string.h> main() { static char str[]="...ab..cd,,ef.hi"; printf("|%s|\n", strtok(str, ".")); printf("|%s|\n", strtok(NULL, ",")); printf("|%s|\n", strtok(NULL, ",.")); printf("|%s|\n", strtok(NULL, ",.")); }Running this example program produces the following results:
$ RUN STRTOK_EXAMPLE1 |ab| |.cd| |ef| |hi| $
#include <stdio.h> #include <string.h> main() { char *ptr, string[30]; /* ** The first character not in the string "-" is "A". The token ** ends at "C" */ strcpy(string, "ABC"); ptr = strtok(string, "-"); printf ("|%s|\n", ptr); /* ** Returns NULL because no characters not in separator string "-" ** were found (i.e. only separator characters were found) */ strcpy(string, "-"); ptr = strtok(string, "-"); if (ptr == NULL) printf("ptr is NULL\n"); }Running this example program produces the following results:
$ RUN STRTOK_EXAMPLE2 |abc| ptr is NULL $