Syntax
#include <string.h> char *strtok(char *string1, const char *string2);Description
strtok reads string1 as a series of zero or more tokens, and string2 as the set of bytes serving as delimiters of the tokens in string1. The tokens in string1 can be separated by one or more of the delimiters from string2. The tokens in string1 can be located by a series of calls to strtok.
In the first call to strtok for a given string1, strtok searches for the first token in string1, skipping over leading delimiters. A pointer to the first token is returned.
To read the next token from string1, call strtok with a NULL string1 argument. A NULL string1 argument causes strtok to search for the next token in the previous token string. Each delimiter is replaced by a null character. The set of delimiters can vary from call to call, so string2 can take any value.
The first time strtok is called, it returns a pointer to the first token in string1. In later calls with the same token string, strtok returns a pointer to the next token in the string. A NULL pointer is returned when there are no more tokens. All tokens are null-terminated.
Using a loop, this example gathers tokens, separated by blanks or commas, from a string until no tokens are left. After processing the tokens (not shown), the example returns the pointers to the tokens a,string, of, and tokens. The next call to strtok returns NULL, and the loop ends.
#include <stdio.h> #include <string.h> int main(void) { char *token,*string = "a string, of, ,tokens\0,after null terminator"; /* the string pointed to by string is broken up into the tokens "a string", " of", " ", and "tokens" ; the null terminator (\0) is encountered and execution stops after the token "tokens" */ token = strtok(string, ","); do { printf("token: %s\n", token); } while (token = strtok(NULL, ",")); return 0; /**************************************************************************** The output should be: token: a string token: of token: token: tokens ****************************************************************************/ }
Related Information