Strtok function in c – strtok C Library Function

Strtok function in c: The function strtok breaks string str into tokens, which are sequences of contiguous characters separated by any of the characters of string delimiters.

First call of strtok function expects a C string as argument for str, and returns first token. Subsequent calls of strtok function expects a null pointer and uses the next position after the end of the last token as the new starting location for scanning.

It appends terminating null character at the end of every token and returns a pointer to the first character of token.

Function prototype of strtok

char *strtok(char *str, const char *delimiters);
  • str : The string to be scanned and broken into smaller sub strings(tokens).
  • delimiters : The string containing the delimiter characters. It can be different from one call to another.

Return value of strtok

C strtok: This function returns a pointer to the beginning of the token, If any token is found in string, otherwise a null pointer. A null pointer is returned if there are no tokens left in input string.

C program using strtok function

Strtok in c: The following program shows the use of strtok function to split a string into tokens.

strtok C Library Function

#include <string.h>
#include <stdio.h>
#include <conio.h>
 
int main() {
   char string[100], delimiters[20];
   char *token;
    
   printf("Enter a string\n");
   scanf("%s", &string);
   printf("Enter string to delimiters\n");
   scanf("%s", &delimiters);
    
   token = strtok(string, delimiters);
    
   printf("List of tokens\n");
   while(NULL != token) 
   {
       printf("%s\n", token);
       token = strtok(NULL, delimiters);
   }
    
   getch();
   return(0);
}

Output

Enter a string
The.quick_brown.fox.jumps$over_the$lazy.dog
Enter string to delimiters
$_.
List of tokens
The
quick
brown
fox
jumps
over
the
lazy
dog