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
asked Dec 21, 2017 by anonymous

1 Answer

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 1\n\n\nline 3\nline 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 Jan 2 by Eric Z Ma (44,200 points)

Please log in or register to answer this question.

Copyright © SysTutorials. User contributions licensed under cc-wiki with attribution required.
Hosted on Dreamhost

...