C String Functions - C strtok

Parses a string into a sequence of tokens. Returns a pointer to the first token in str1. If no token is found then a null pointer is returned.

char *strtok(char *str1 , const char *str2 );

If str1 and str2 are not null, then the following search sequence begins.

The first character in str1 that does not occur in str2 is found.

If str1 consists entirely of characters specified in str2, then no tokens exist and a null pointer is returned.

If this character is found, then this marks the beginning of the first token.

It then begins searching for the next character after that which is contained in str2.

If this character is not found, then the current token extends to the end of str1.

If the character is found, then it is overwritten by a null character, which terminates the current token.


char * strtok ( char * str, const char * delimiters );


This function has the following parameter.

C string to truncate.
the delimiter characters.


If a token is found, a pointer to the beginning of the token.

Otherwise, a null pointer.


#include <stdio.h>
#include <string.h>
/*from   ww w.  j a va2  s  .  c  om*/
int main (){
  char str[] ="- This is a test string.";
  char * pch;
  printf ("Splitting string \"%s\" into tokens:\n",str);
  pch = strtok (str," ,.-");
  while (pch != NULL){
    printf ("%s\n",pch);
    pch = strtok (NULL, " ,.-");
  return 0;


The code above generates the following result.

Example 2

/*  ww w .jav a 2s .co m*/
int main(void) { 

   char search_string[]="this is a test"; 
   char *array[50]; 
   int loop; 

   array[0]=strtok(search_string," "); 
   if(array[0]==NULL) { 
     printf("No test to search.\n"); 

   for(loop=1;loop<50;loop++) { 
     array[loop]=strtok(NULL," "); 

   for(loop=0;loop<50;loop++) { 
     printf("Item #%d is %s.\n",loop,array[loop]); 
   return 0; 

The code above generates the following result.

Example 3

#include <string.h>
#include <stdio.h>
 //w ww  .  ja  v a2 s .c  o m
int main(void){
    char input[] = "this is a test";
    printf("Parsing the input string '%s'\n", input);
    char *token = strtok(input, " ");
    while(token) {
        token = strtok(NULL, " ");
    for(size_t n = 0; n < sizeof input; ++n)
        input[n] ? printf("%c", input[n]) : printf("\\0");

The code above generates the following result.