Break a string into tokens


#include <string.h>

char* strtok( char* s, 
              const char* sep );


NULL, or the string that you want to break into tokens; see below.
A set of the characters that separate the tokens.



Use the -l c option to qcc to link against this library. This library is usually included automatically.


The strtok() function breaks the string pointed to by s into a sequence of tokens, each of which is delimited by a character from the string pointed to by sep.

The first call to strtok() returns a pointer to the first token in the string pointed to by s. Subsequent calls to strtok() must pass a NULL pointer as the first argument, in order to get the next token in the string. The set of delimiters used in each of these calls to strtok() can be different from one call to the next.

The first call in the sequence searches s for the first character that isn't contained in the current delimiter string sep. If no such character is found, then there are no tokens in s, and strtok() returns a NULL pointer. If such a character is found, it's the start of the first token.

The strtok() function then searches from there for a character that's contained in the current delimiter string. If no such character is found, the current token extends to the end of the string pointed to by s. If such a character is found, it's overwritten by a null character, which terminates the current token. The strtok() function saves a pointer to the following character, from which the next search for a token will start when the first argument is a NULL pointer.

Note: You might want to keep a copy of the original string because strtok() is likely to modify it.


A pointer to the token found, or NULL if no token was found.


#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main( void )
    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 );
    return EXIT_SUCCESS;

produces the output:

Find words, all of them.
word: Find
word: words
word: all
word: of
word: them


ANSI, POSIX 1003.1

Cancellation point No
Interrupt handler No
Signal handler No
Thread No