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

Posted on In Programming, Tutorial

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

Method 1: use `erase()` and `remove()`

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

Method 2: use `regex_replace()`

Use a regular expression to match consequence \ns and replace the matched strings with "" (empty string).

#include <iostream>
#include <algorithm>
#include <regex>

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

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

  std::regex newlines_re("\n+");

  auto result = std::regex_replace(input, newlines_re, "");

  std::cout << "After:\n" << result << "\n";

  return 0;
}

Execution results:

input:
line 1

line 3
line 4
After:
line 1line 3line 4

Eric Ma

Eric is a 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.

3 comments

  1. I tried this, but it’s giving me error C2678( binary ‘==’: no operator found which takes a left-hand operand of type ‘std::vector<std::string,std::allocator>’ (or there is no acceptable conversion) in the algorithm file!

  2. Great post!
    Can you help me with getting an output of the form
    “line 1 line 3 line 4”
    instead of “line 1line 3line 4”

    1. You can first replace ‘\n’ with ‘ ‘ and then use `std::unique()` with a lambda to remove duplicated spaces (if duplicated spaces are fine to be removed too).

      #include <iostream>
      #include <algorithm>
      
      int main ()
      {
        std::string input{"line 1\n\n\nline 3\nline 4"};
      
        std::cout << "input:\n" << input << "\n";
      
        std::replace(input.begin(), input.end(), '\n', ' ');
      
        input.erase(std::unique(input.begin(), input.end(), [](char lhs, char rhs) {
          return lhs == rhs && lhs == ' ';
        }), input.end());
      
        std::cout << "After:\n" << input << "\n";
      
        return 0;
      }

      You may also use regular expression to do so (and it is fine if the lines contains duplicated spaces):

      #include <iostream>
      #include <algorithm>
      #include <regex>
      
      int main ()
      {
        std::string input{"line 1\n\n\nline 3\nline 4"};
      
        std::cout << "input:\n" << input << "\n";
      
        std::regex newlines_re("\n+");
      
        auto result = std::regex_replace(input, newlines_re, " ");
      
        std::cout << "After:\n" << result << "\n";
      
        return 0;
      }

Leave a Reply

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