This post will discuss how to parse a comma separated string in C++.

1. Using String Stream

The standard solution to split a comma-delimited string is using std::stringstream. The following demonstrates its usage by reading one character at a time and discarding the immediate character (i.e., comma).

Download  Run Code

Output:

1 2 3 4 5

 
The code can be easily extended to handle multiple consecutive separators or whitespace in the string using a while loop instead of the if-statement.

Download  Run Code

Output:

1 2 3 4 5

 
Both above solutions put the results in an integer vector and return it. The code can be easily modified to construct a vector of strings.

Download  Run Code

Output:

1 2 3 4 5

2. Using std::string::find function

Another solution is to use the std::string::find function to get the next position of the delimiter in the string and insert the substring between the last delimiter position and the current delimiter position into a vector.

The following code demonstrates this by constructing a vector of integers but can be easily modified to construct a vector of strings and handle bad input (consecutive separators, whitespace, etc.).

Download  Run Code

Output:

1 2 3 4 5

3. Using regular expressions

Another plausible solution to parse a comma-delimited string is using a regular expression. Regular expressions are the standardized way to perform a pattern match against a sequence.

Download  Run Code

Output:

1 2 3 4 5

4. 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:

1 2 3 4 5

 
The Boost library also provides boost::algorithm::split function to tokenize an expression, which is equivalent to strtok function in C. The boost::algorithm::split function split the input sequence into tokens, delimited by the separators given using a predicate.

Download Code

Output:

1 2 3 4 5

That’s all about parsing a comma-delimited string in C++.