Whats the most efficient way of removing a 'newline' from a std::string?
13 Answers
#include <algorithm>
#include <string>
std::string str;
str.erase(std::remove(str.begin(), str.end(), '\n'), str.cend());
The behavior of std::remove
may not quite be what you'd expect.
A call to remove is typically followed by a call to a container's erase method, which erases the unspecified values and reduces the physical size of the container to match its new logical size.
See an explanation of it here.

- 36,103
- 8
- 58
- 81
-
7If there's any chance of newlines from other platforms, maybe delete '\r' characters too. A second call to erase and std::remove etc is no big deal performance-wise. Alternatives, such as using std::remove_if with a predicate function, will probably be slower. – Sep 28 '09 at 19:46
-
If your data was originally loaded from a file opened in text (ascii, non-binary) mode I believe it automatically converts all newline conventions to a simple '\n'. I'm looking for a definitive reference to corroborate. – luke Sep 29 '09 at 13:56
-
http://msdn.microsoft.com/en-us/library/kt0etdcs%28VS.71%29.aspx -- thats for fread(), but I believe iostream reads and writes have the same behavior. – luke Sep 29 '09 at 14:06
-
The key sentence in the `std::remove` reference is *"A call to remove is typically followed by a call to a container's erase method, which erases the unspecified values and reduces the physical size of the container to match its new logical size."* – wcochran Nov 29 '17 at 21:18
-
2last parameter of last line can be `cend()` like `str.erase(std::remove(str.begin(), str.end(), '\n'), str.cend());` – Oğuzhan Türk Sep 17 '21 at 08:35
If the newline is expected to be at the end of the string, then:
if (!s.empty() && s[s.length()-1] == '\n') {
s.erase(s.length()-1);
}
If the string can contain many newlines anywhere in the string:
std::string::size_type i = 0;
while (i < s.length()) {
i = s.find('\n', i);
if (i == std::string:npos) {
break;
}
s.erase(i);
}

- 951,095
- 183
- 1,149
- 1,285
-
3First version perfect. Second version would be easier to use std::erase(std::removr(XXX)) – Martin York Sep 28 '09 at 19:13
-
1I've never been terribly comfortable with the semantics of remove() and always have to look it up because it's not obvious. My above implementation is simple and direct, but not the most efficient. If efficiency is important, a slightly different solution is needed. – Greg Hewgill Sep 28 '09 at 19:57
-
1the question was, "what's the most efficient way...", so I guess efficiency is important ;) – Pieter Sep 28 '09 at 22:53
-
1[Here's the newer, C++ version of the first part of your code.](https://stackoverflow.com/a/71565411/4561887) – Gabriel Staples Mar 21 '22 at 23:52
You should use the erase-remove idiom, looking for '\n'
. This will work for any standard sequence container; not just string
.
Here is one for DOS or Unix new line:
void chomp( string &s)
{
int pos;
if((pos=s.find('\n')) != string::npos)
s.erase(pos);
}

- 2,057
- 24
- 16
-
6Change the `if` to a `while` loop and you have a pretty good solution. – CaptainBli May 01 '15 at 17:26
Slight modification on edW's solution to remove all exisiting endline chars
void chomp(string &s){
size_t pos;
while (((pos=s.find('\n')) != string::npos))
s.erase(pos,1);
}
Note that size_t is typed for pos, it is because npos is defined differently for different types, for example, -1 (unsigned int) and -1 (unsigned float) are not the same, due to the fact the max size of each type are different. Therefore, comparing int to size_t might return false even if their values are both -1.

- 21
- 2
The code removes all newlines from the string str
.
O(N) implementation best served without comments on SO and with comments in production.
unsigned shift=0;
for (unsigned i=0; i<length(str); ++i){
if (str[i] == '\n') {
++shift;
}else{
str[i-shift] = str[i];
}
}
str.resize(str.length() - shift);

- 96,026
- 17
- 121
- 165
std::string some_str = SOME_VAL;
if ( some_str.size() > 0 && some_str[some_str.length()-1] == '\n' )
some_str.resize( some_str.length()-1 );
or (removes several newlines at the end)
some_str.resize( some_str.find_last_not_of(L"\n")+1 );

- 97,037
- 24
- 136
- 212
Another way to do it in the for loop
void rm_nl(string &s) {
for (int p = s.find("\n"); p != (int) string::npos; p = s.find("\n"))
s.erase(p,1);
}
Usage:
string data = "\naaa\nbbb\nccc\nddd\n";
rm_nl(data);
cout << data; // data = aaabbbcccddd

- 3,390
- 1
- 26
- 37
To extend @Greg Hewgill's answer for C++11:
If you just need to delete a newline at the very end of the string:
This in C++98:
if (!s.empty() && s[s.length()-1] == '\n') {
s.erase(s.length()-1);
}
...can now be done like this in C++11:
if (!s.empty() && s.back() == '\n') {
s.pop_back();
}
Optionally, wrap it up in a function. Note that I pass it by ptr here simply so that when you take its address as you pass it to the function, it reminds you that the string will be modified in place inside the function.
void remove_trailing_newline(std::string* str)
{
if (str->empty())
{
return;
}
if (str->back() == '\n')
{
str->pop_back();
}
}
// usage
std::string str = "some string\n";
remove_trailing_newline(&str);
Whats the most efficient way of removing a 'newline' from a
std::string
?
As far as the most efficient way goes--that I'd have to speed test/profile and see. I'll see if I can get back to you on that and run some speed tests between the top two answers here, and a C-style way like I did here: Removing elements from array in C. I'll use my nanos()
timestamp function for speed testing.
Other References:
- See these "new" C++11 functions in this reference wiki here: https://en.cppreference.com/w/cpp/string/basic_string
- https://en.cppreference.com/w/cpp/string/basic_string/empty
- https://en.cppreference.com/w/cpp/string/basic_string/back
- https://en.cppreference.com/w/cpp/string/basic_string/pop_back

- 36,492
- 15
- 194
- 265
If its anywhere in the string than you can't do better than O(n).
And the only way is to search for '\n' in the string and erase it.
for(int i=0;i<s.length();i++) if(s[i]=='\n') s.erase(s.begin()+i);
For more newlines than:
int n=0;
for(int i=0;i<s.length();i++){
if(s[i]=='\n'){
n++;//we increase the number of newlines we have found so far
}else{
s[i-n]=s[i];
}
}
s.resize(s.length()-n);//to delete only once the last n elements witch are now newlines
It erases all the newlines once.

- 4,742
- 9
- 33
- 46
-
1This implementation will not handle consecutive newlines properly, since `i` is incremented regardless of whether an element is erased. – Greg Hewgill Sep 28 '09 at 19:08
All these answers seem a bit heavy to me.
If you just flat out remove the '\n' and move everything else back a spot, you are liable to have some characters slammed together in a weird-looking way. So why not just do the simple (and most efficient) thing: Replace all '\n's with spaces?
for (int i = 0; i < str.length();i++) {
if (str[i] == '\n') {
str[i] = ' ';
}
}
There may be ways to improve the speed of this at the edges, but it will be way quicker than moving whole chunks of the string around in memory.

- 44,016
- 10
- 73
- 134
About answer 3 removing only the last \n off string code :
if (!s.empty() && s[s.length()-1] == '\n') {
s.erase(s.length()-1);
}
Will the if condition not fail if the string is really empty ?
Is it not better to do :
if (!s.empty())
{
if (s[s.length()-1] == '\n')
s.erase(s.length()-1);
}

- 31
- 1
- 6
-
1No, the first version should abort the if statement when the string is empty – underdoeg Aug 07 '19 at 19:13