strtok
Breaks a string into a sequence of tokens, each of which is delimited by a character from another string
#include <string.h> char *strtok ( char *s1, const char *s2);
If a delimiter is found, returns a pointer to the first byte of a token. On subsequent iterations if no delimiter is found, returns a null pointer.
If the string does not contain any of the delimiters specified in sepset, returns a pointer to the string. All of the string is considered to be a token.
The strtok function is used to break the string pointed to by s1 into a sequence of tokens, each of which is delimited by a character from the string pointed to by s2. For example, suppose that s1 and s2 contain the following characters:
s1: "abcd:efgh:ijkl" s2: ":"
The first call to strtok would return a pointer to a, since abcd is the first token. The second call to strtok would return a pointer to e, because efgh is the second token. The second and subsequent calls to strtok must pass a null pointer as the first argument, in order to get the next token in the string. The strtok function saves a pointer to the following character, from which the next search for a token starts when the first argument is a null pointer.
The strtok function replaces each delimiter that it finds with a null character, which terminates the current token. Because strtok can modify the original string, that string should be duplicated if the string is to be reused.
The set of delimiters used in the calls to strtok can be different from one call to the next.
#include <string.h> main () { char *p; char *buffer; char *delims = { " .," }; buffer = strdup ("Find words, all of them."); printf ("%s\n", buffer); p = strtok (buffer, delims); while (p != NULL) { printf ("word: %s\n", p); p = strtok (NULL, delims); } printf ("%s\n", buffer ); }
produces the following:
Find words, all of them. word: Find word: words word: all word: of word: them Find