strtok Function

Break a string into substrings, or tokens, by inserting null characters in place of specified delimiters.




char *strtok(char *s1, const char *s2);


pointer to the null terminated string to be searched
pointer to characters to be searched for (used as delimiters)

Return Value

Returns a pointer to the first character of a token (the first character in a sequence of characters in s1 that does not appear in the set of characters of s2). If no token is found, the null pointer is returned.


A sequence of calls to this function can be used to split up a string into substrings (or tokens) by replacing specified characters with null characters. The first time this function is invoked on a particular string, that string should be passed in s1. After the first time, this function can continue parsing the string from the last delimiter by invoking it with a null value passed in s1.

It skips all leading characters that appear in the string s2 (delimiters), then skips all characters not appearing in s2 (this segment of characters is the token), and then overwrites the next character with a null character, terminating the current token. The function, strtok, then saves a pointer to the character that follows, from which the next search will start. If strtok finds the end of the string before it finds a delimiter, the current token extends to the end of the string pointed to by s1. If that was the first call to strtok, it does not modify the string (no null characters are written to s1). The set of characters that is passed in s2 need not be the same for each call to strtok.

If strtok is called with a non-null parameter for s1 after the initial call, the string becomes the new string to search. The old string previously searched will be lost.


See the notes at the beginning of this chapter or section for information on using printf() or scanf() (and other functions reading and writing the stdin or stdout streams) in the example code.

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

int main(void)
  char str1[30] = "Here, on top of the world!";
  char delim[5] = ", .";
  char *word;
  int x;

  printf("str1 : %s\n", str1);
  x = 1;
  word = strtok(str1,delim);
  while (word != NULL)
    printf("word %d: %s\n", x++, word);
    word = strtok(NULL, delim);

Example Output

str1 : Here, on top of the world!
word 1: Here
word 2: on
word 3: top
word 4: of
word 5: the
word 6: world!