strtok() - Manipulation Function

How to split a string into tokens in C++?

Explanation

strtok() manipulation function is used to split a string into tokens. It returns a pointer to next token in the "str1", the characters of "str2" are the delimiters for the token. Function returns a NULL pointer if there are no tokens to return. When this function is called for the first time, "str1" point to string being tokenized and then a NULL pointer is used for "str1". Different delimiters can be used every time the strok() is called.

Syntax:


char *strtok (char *str1, const char *str2);

Example :



#include <stdio.h>
#include <cstring.h>
int main ()
{
char str1[] = "Its* time*have* fun";
char str2[] = "*";
char * pnt;
pnt=strtok( str1, str2 );
while( pnt!= NULL )
{
printf( "Tokenized string using * is:: %s\n", pnt );
pnt = strtok( NULL, str2 );
}
}

Result :

Tokenized string using * is:: Its
Tokenized string using * is:: time
Tokenized string using * is:: have
Tokenized string using * is:: fun

In the above example, "strtok()" manipulation function is used tokenize based on the delimiter "*". It splits it into tokens by the delimiters everytime it is called.

C++ Tutorial


Ask Questions

Ask Question