This post will discuss how to split a string on newlines in C++.

1. Using std::getline

A simple solution to split a string on newlines is using the std::getline function. It can be used to extract tokens from the input stream delimited by the newline, as shown below:

Download Code

Output:

C
C++
Java

2. Using string::find

The std::string::find member function searches a string for the specified character, starting from the specified position. It returns the first occurrence of the specified character and string::npos if it is not found. It can be used as follows to split a string on newlines:

Download  Run Code

Output:

C
C++
Java

3. Using Boost

Finally, we can use the boost::algorithm::split_regex algorithm offered by the boost library to split the input sequence into tokens, separated by separators. This function is equivalent to C strtok and is available in the header <boost/algorithm/string/regex.hpp>.

Download Code

Output:

C
C++
Java

That’s all about splitting a string on newlines in C++.