How to remove newline characters from a string in C++?
Posted on In Programming, TutorialHow 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 \n
s.
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 \n
s 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
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!
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”
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).
You may also use regular expression to do so (and it is fine if the lines contains duplicated spaces):