C++ Standard Library C++ STL Library

C++ <cstring> - strtok() Function



The C++ <cstring> strtok() function splits a null-terminated byte string pointed to by str using the delimiter characters identified by null-terminated byte string pointed to by delim. This function is designed to be called multiple times to obtain successive tokens from the same string.

Only the first call, the function expects a C string as argument for str, whose first character is used as the starting point to scan for tokens. Every subsequent call, the function expects null pointer and uses the position right after the end of the last token as the new starting location for scanning.

Syntax

char * strtok ( char * str, const char * delim );                 

Parameters

str Specify pointer to the null-terminated byte string to tokenize.
delim Specify pointer to the null-terminated byte string identifying delimiters.

Return Value

Returns pointer to the beginning of the next token or a null pointer if there are no more tokens.

Example:

The example below shows the usage of strtok() function.

#include <iostream>
#include <cstring>
using namespace std;
 
int main (){
  char MyStr[100] = "To be, or not to be, that is the question.";
  char delim[] = ",#@ ";
  
  //getting the first token
  char * token = strtok(MyStr, delim);

  //searching for all tokens and displaying it
  while(token != NULL) {
    cout<<token<<"\n";
    token = strtok(NULL, delim);
  }
 
  return 0;
}

The output of the above code will be:

To
be
or
not
to
be
that
is
the
question.

❮ C++ <cstring> Library