strtok()

The strtok() function breaks a string into a series of tokens using a list of delimiters.

Syntax

char *token = strtok(string, delimiters);

token = strtok(NULL, delimiters);

The strtok() function splits the string parameter into tokens based on one or more delimiters, and returns the pointer to the first token.

Subsequent calls to strtok(), with string set to NULL, return a pointer to the next tokenized string. When there are no tokens left to retrieve, a NULL pointer is returned.

Example

The following example splits up a comma-delimited list and prints out the result:

#include <string.h>
#include <stdio.h>
int main () {
char str[] = "Comma,Delimited,List";
const char s[] = ",";
char *token = strtok(str, s);
while( token != NULL ) {
printf( "%s\n", token );
token = strtok(NULL, s);
}
}

This results in the following output:

Comma
Delimited
List

Contributors

Interested in helping build Docs? Read the Contribution Guide or share your thoughts in this feedback form.

Learn C on Codecademy