This post will discuss how to tokenize a string in C++.

1. Using String Stream

The common solution to tokenize a string in C++ is using std::istringstream, which is a stream class to operate on strings. The following code extract tokens from the stream using the extraction operator and insert them into a container.

Download  Run Code

Output:

Tokenize
a
string
in
C++

 
Here’s another approach to extract tokens from an input string using std::istream_iterator. The std::istream_iterator skip whitespace by default unless disabled with std::noskipws.

Download  Run Code

Output:

Tokenize
a
string
in
C++

 
The code can be further shortened to the following using the initializer list:

Download  Run Code

Output:

Tokenize
a
string
in
C++

2. Using regular expressions

Another plausible solution to tokenize a string is using a regular expression, which is the standard for performing a pattern match against a sequence.

Download  Run Code

Output:

Tokenize
a
string
in
C++

3. Using Boost library

The Boost C++ library also offers several utility classes for this task. The Boost tokenizer class provides a view of tokens contained in a sequence by interpreting certain characters as separators.

Download Code

Output:

Tokenize
a
string
in
C++

That’s all about tokenizing a string in C++.