The strtok() function is used in tokenizing a string based on a delimiter. It is present in the header file “string.h” and returns a pointer to the next token if present, if the next token is not present it returns NULL. To get all the tokens the idea is to call this function in a loop.

Header File:

#include <string.h>

Syntax:

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

In this article, we will discuss the implementation of this function in which two things must be taken into consideration:

  • Maintain the state of the string to make sure how many tokens we have already extracted.
  • Secondly, maintain the list of extracted tokens in an array to return it.

Steps:

  • Create a function strtok() which accepts string and delimiter as an argument and return char pointer.
  • Create a static variable input to maintain the state of the string.
  • Check if extracting the tokens for the first time then initialize the input with it.
  • If the input is NULL and all the tokens are extracted then return NULL.
  • In this step, start extracting tokens and store them in the array result[].
  • Now, iterate a loop until NULL occurs or the delimiter then return the result by including ‘\0’.
  • When the end of the string is reached and if it requires then manually add a ‘\0‘ and include this corner case in the end.

#c++ #c++ programs #strings #cpp-library #cpp-string

Implementing of strtok() function in C++
5.65 GEEK