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.
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.
- 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.
Below is the implementation of the same:
It, is my, day
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
In case you wish to attend live classes with industry experts, please refer Geeks Classes Live