strtok() Function In C

C programming language provides the strtok() function in order to break a string into multiple tokens using the specified delimiter. As an example, a command-separated CSV file can be easily parsed with the strtok() function by using the comma as the delimiter.

strtok() Function Syntax

The syntax of the strtok() function is like below. This function returns a pointer to the first token of the string.

char *strtok(char *STR, const char *DELIMETER)
  • *STR is a string or character pointer which will be parted into tokens.
  • *DELIMETER is the delimeter which is used to parse given *STRING into multiple tokens.

Parse String with strtok() Function

The strtok() function can be used to parse a string into substring or tokens by providing the delimiter. In this example, we use ; as delimeter.

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

int main () {
   char str[] = "www,wisetut,com";
   const char delimeter[] = ",";
   char *token;
   
   /* return the first token */
   token = strtok(str, delimeter);
   
   /* walk through other tokens until end*/
   while( token != NULL ) {
      printf( " %s\n", token );
    
      token = strtok(NULL, delimeter);
   }
   
   return(0);
}

The output will be like below.

www
wisetut
com

Leave a Comment