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.
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] !=
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] .
Iterator – based Approach: The string can be traversed using iterator.
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"
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With