strtok() in C
Overview
The strtok in c is a library function which breaks the given string into a series of tokens using the delimiter passed as a parameter. Like if there is a string with multiple words separated by comma then we can use this function strtok in c with comma(,) as a delimiter to split this string based on comma. The delimiter can be anything like a number,character, space or special characters.
Syntax of strtok() in C
The syntax of function strtok in c Language is given below:
Parameters of strtok() in C
string − This is the string which is passed as the parameter which is to be modified by this function.
delimiter − This is the string containing the delimiter on the basis of which string will be broken into series of tokens.And these may vary from one call to another.
Return Value of strtok() in C
The return value of this function is a pointer to the first token which is found in the string on breaking it into several tokens. And if there will be no tokens left to retrieve, a null pointer is returned.
Example
A program which splits a string using function strtok in c.
**Output of this program would be - **
Exceptions of strtok() in C
There are not any exceptions of function strtok in c and it works the same way for all cases. If the delimiter is not present in the string , then it returns NULL as the token.
What is strtok() in C?
strtok() is a function in C language which take a string and a delimeter then breaks the given string into a series of tokens using the delimiter passed as a parameter. It then return pointer to the first token which is found in the string on breaking it into several tokens.
More Examples
Code of function strtok in c to describe practical application of the function using splitting the string.
Output of this program would be -
Conclusion
- strtok in c is used to split a string in multiple strings on the basis of separators or delimiters. We can also implement CSV file using this strtok() function as CSV files are separated by commas which is a delimiter in that function.
- This function can be used to split any string or multiple strings based on the delimiter provided.
- #include <string.h> This header file should always be included when we run the program consisting of strtok() function.
- The delimiter can be anything like alphabet,numeric characters,special characters etc.
- We can also import a csv file and apply this function to get the required result by splitting the file based on the delimiter.