here's what I need to do. I have a string in C++. For every line in the string, I need to append a few characters (like ">> ") to the beginning of the line. What I am struggling with is a good way to split the string around newlines, iterate through the elements appending the characters, and then rejoin the string together. I've seen a few ideas, such as strtok()
, but I was hoping c++ strings would have something a little more elegant.
Asked
Active
Viewed 1.7k times
17

ewok
- 20,148
- 51
- 149
- 254
-
3Hope this http://stackoverflow.com/questions/236129/splitting-a-string-in-c could help – halfelf Sep 20 '12 at 14:15
4 Answers
29
Here's a straight-forward solution. Maybe not the most efficient, but unless this is hot code or the string is huge, it should do fine. We suppose that your input string is called input
:
#include <string>
#include <sstream>
std::string result;
std::istringstream iss(input);
for (std::string line; std::getline(iss, line); )
{
result += ">> " + line + "\n";
}
// now use "result"

Kerrek SB
- 464,522
- 92
- 875
- 1,084
5
A more functional approach would be to use a getline
-based iterator as shown in this answer and then use that with std::transform
for transforming all input lines, like this:
std::string transmogrify( const std::string &s ) {
struct Local {
static std::string indentLine( const std::string &s ) {
return ">> " + s;
}
};
std::istringstream input( s );
std::ostringstream output;
std::transform( std::istream_iterator<line>( input ),
std::istream_iterator<line>(),
std::ostream_iterator<std::string>( output, "\n" ),
Local::indentLine );
return output.str();
}
The indentLine
helper actually indents the line, the newlines are inserted by the ostream_iterator
.

Community
- 1
- 1

Frerich Raabe
- 90,689
- 19
- 115
- 207
3
If the data in your string is basically like a file, try using std::stringstream
.
std::istringstream lines( string_of_lines );
std::ostringstream indented_lines;
std::string one_line;
while ( getline( lines, one_line ) ) {
indented_lines << ">> " << one_line << '\n';
}
std::cout << indented_lines.str();

Potatoswatter
- 134,909
- 25
- 265
- 421
1
You can wrap it in a stringstream
and use std::getline
to extract a line at a time:
std::string transmogrify(std::string const & in) {
std::istringstream ss(in);
std::string line, out;
while (getline(ss, line)) {
out += ">> ";
out += line;
out += '\n';
}
return out;
}

Mike Seymour
- 249,747
- 28
- 448
- 644