3.13. strtok

char *strtok( char * restrict s1, const char * restrict s2);
strtok searches s1 for tokens delimited by characters from s2.

A sequence of calls of strtok( s1, s2) splits s1 into tokens, each delimited by a character from s2.

The first call in a sequence has a non-NULL s1. It finds the first token in s1 consisting of characters not in s2; it terminates that by overwriting the next character of s1 with '\0' and returns a pointer to the token.

Each subsequent call, indicated by a NULL value of s1, returns the next such token, searching from just past the end of the previous one.

strtok returns NULL when no further token is found.

The string s2 may be different on each call.

strtok has to keep a static local variable to keep track of where it stopped in the string the last time it was called, i.e.

        static char *p = NULL;
strtok is useful for splitting a line into separate words.

For example, with lines of input like

copy Amat b
the program fragment below uses strtok in the copy() function, which does not have direct access to the line variable in main:
#include <stdio.h>
#include <string.h>

#define SPACE " \t\n"           /* whitespace on input lines */
...
void copy( void)
{
    char *from = strtok( NULL, SPACE);
    char *to = strtok( NULL, SPACE);
    char *extra = strtok( NULL, SPACE);

    if( from == NULL  ||  to == NULL  ||  extra != NULL)
    {
        error( "copy takes two arguments");
        return;
    }

    if( strcmp( from, to) != 0)
        mm_copy( from, to);
}
...
int main( void)
{
    char line[BUFSIZ];          /* one line of user input */
    char *word;                 /* pointer to one word of the input line */

    while( fgets( line, BUFSIZ, stdin) )
    {
        if( (word = strtok( line, SPACE)) == NULL)      /* empty line */
            continue;

        ... check for matching command, call a function like copy() above
    }
}