Home > Software design >  C process string one by line
C process string one by line

Time:02-01

So I have string:

string message = "Hello\nHow are you?\nGood!"

I want to get it line by line in this format:

string line = "";

for (getline(message, line)) {
    // do something with the line
}

How can I achieve this? It doesn't matter if getline will be in use.

I tried to split the string by \n but I can't go through it with for loop

CodePudding user response:

getline requires an input stream to work on. Fortunately, we have std::stringstream which you can probably tell from the name is a stream of a string. Using that changes your code to

std::string line;
std::stringstream ss(message);
while(getline(ss, line)) {
    // do something with the line
}

CodePudding user response:

Using ranges, you can do this with a loop over a split view:

for (auto line_view : std::ranges::split_view(message, "\n")) {
    std::string_view line{line_view.begin(), line_view.end()};
    // do something with the line
}

Demo

This can avoid making multiple copies of the original string and each line, which may be worth the extra complexity depending on the size of the string.

  • Related