Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iterate through lines in a string c++

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.

like image 477
ewok Avatar asked Sep 20 '12 14:09

ewok


People also ask

How to traverse through each character in a string in C?

Use strlen() to get the length of the string. for(int i = 0; i < strlen(full_name); i++) { printf("%c", full_name[i]); } Since the string is terminated by '\0', which is 0 in ASCII value, you can also use full_name[i] !=

How do I iterate through a string?

One way to iterate over a string is to use for i in range(len(str)): . In this loop, the variable i receives the index so that each character can be accessed using str[i] .

Can iterator be used for string?

Iterator – based Approach: The string can be traversed using iterator.


2 Answers

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"
like image 134
Kerrek SB Avatar answered Sep 23 '22 22:09

Kerrek SB


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.

like image 39
Frerich Raabe Avatar answered Sep 22 '22 22:09

Frerich Raabe