// A C++ program for splitting a string using strtok()
#include <stdio.h>
#include <string.h>
int main()
{
char str[] = "First-Demo-Example";
char *token = strtok(str, "-"); // Returns first token
while (token != NULL)// Keep printing tokens while the delimiters present in str[]
{
printf("%s\n", token);
token = strtok(NULL, "-");
}
return 0;
}
Output:
First
Demo
Example
Explanation:
Syntax of strok method:
char * strtok ( char * str, const char * delimiters );
The working of strtok runtime function, the first time when strtok is called, a string is passed which need to be tokenize. In above example, str is the string passed and "-" is the delimiter. 'str' is searched until the "-" character is found, the first token is returned ('First') and token points to that first detached string. In order to get next token and to continue with the same string NULL is passed as first argument since strtok maintains a static pointer to previous passed string and it continues until no more "-" can be found, then the last string is returned as the last token 'Example'.
0 Comment(s)