This post will discuss how to split a string in C++ using a delimiter and construct a vector of strings containing individual strings.

C++ standard library didn’t provide any built-in function for this concrete task. This post provides an overview of some of the available alternatives to accomplish this.

1. Using find_first_not_of() with find() function

We can use a combination of string’s find_first_not_of() and find() functions to split a string in C++, as shown below:

Download  Run Code

Output:

C
C++
Java

2. Using getline() function

Another good alternative is to use the std::getline function, which extracts characters from the istream object and stores them into a specified stream until the delimitation character is found.

Download  Run Code

Output:

C
C++
Java

3. Using std::regex_token_iterator function

Another solution is to use the std::sregex_token_iterator which is a specialization of std::regex_token_iterator<std::string::const_iterator>

Download  Run Code

Output:

C
C++
Java

4. Use std::strtok function

We can also use the strtok() function to split a string into tokens, as shown below:

Download  Run Code

Output:

C
C++
Java

5. Using std::string::find function

Finally, we can use std::string::find algorithm with std::string::substr which is demonstrated below:

Download  Run Code

Output:

C
C++
Java

That’s all about splitting a string in C++ using a delimiter.