Using strtok to tokenize a string. - C++ Data Type

C++ examples for Data Type:char array

Description

Using strtok to tokenize a string.

Demo Code

#include <iostream> 
#include <cstring> // prototype for strtok 
using namespace std; 

int main() //from w  w w  .  ja  v a  2s  .  co m
{ 
    char sentence[] = "This is a sentence with tokens. this is a test"; 
    char *tokenPtr; 

    cout << "The string to be tokenized is:\n" << sentence << "\n\nThe tokens are:\n\n"; 

    // begin tokenization of sentence 
    tokenPtr = strtok( sentence, " " ); 

    // continue tokenizing sentence until tokenPtr becomes NULL 
    while ( tokenPtr != NULL ) 
    { 
       cout << tokenPtr << '\n'; 
       tokenPtr = strtok( NULL, " " ); // get next token 
    }

    cout << "\nAfter strtok, sentence = " << sentence << endl; 
}

Result


Related Tutorials