How to remove newline characters from a string in C++?

How to remove newline characters from a string in C++?

For example, a string like

line 1

line 3
line 4

should be converted to

line 1line 3line 4

In short, use this code snippet:

input.erase(std::remove(input.begin(), input.end(), 'n'),
            input.end());

std::remove() shifts all elements that are equal to the value n by moving the elements in the range to the end and returns the past-the-end iterator for the new range of values that are not n.

std::erase() removes elements from the container in the range specified and updates the size of the vector.

For the above piece of code, the range of elements removed are all ns.

A full example program,

#include <iostream>
#include <algorithm>

int main ()
{
  std::string input{"line 1nnnline 3nline 4"};

  std::cout << "input:n" << input << "n";

  input.erase(std::remove(input.begin(), input.end(), 'n'), input.end());

  std::cout << "After:n" << input << "n";

  return 0;
}

Execution outputs:

input:
line 1


line 3
line 4
After:
line 1line 3line 4
Answered by Eric Z Ma.

Eric Z Ma

Eric is a father and systems guy. Eric is interested in building high-performance and scalable distributed systems and related technologies. The views or opinions expressed here are solely Eric's own and do not necessarily represent those of any third parties.

Leave a Reply

Your email address will not be published. Required fields are marked *