[Previous]
[Contents]
[Next]

strtok(), _fstrtok()

break a string into tokens

Synopsis:

#include <string.h>
char *strtok( char *s1, const char *s2 );
char __far *_fstrtok( char __far *s1,
                      const char __far *s2 );

Description:

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.

The first call to strtok() returns a pointer to the first token in the string pointed to by s1. 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 s1 for the first character that is not contained in the current delimiter string s2. If no such character is found, then there are no tokens in s1, and the strtok() function returns a NULL pointer. If such a character is found, it is the start of the first token.

The strtok() function then searches from there for a character that is 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 s1. If such a character is found, it is 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: Because strtok() may modify the original string, that string should be duplicated if the string is to be re-used.

The _fstrtok() function is a data-model-independent form of the strtok() function. It accepts far pointer arguments, and returns a far pointer. It is most useful in mixed memory model applications.

Returns:

A pointer to the first character of a token, or NULL if no token was found.

Examples:

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

void 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 output:

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

Classification:

strtok() is ANSI; _fstrtok() is WATCOM.
Safety:
Interrupt handler No
Signal handler No
Thread No

See also:

strcspn(), strpbrk()


[Previous]
[Contents]
[Next]