136

How do I remove the carriage return character (\r) and the Unix newline character(\n) from the end of a string?

Henke
  • 4,445
  • 3
  • 31
  • 44
Avik
  • 2,097
  • 7
  • 24
  • 30

13 Answers13

228

This will trim off any combination of carriage returns and newlines from the end of s:

s = s.TrimEnd(new char[] { '\r', '\n' });

Edit: Or as JP kindly points out, you can spell that more succinctly as:

s = s.TrimEnd('\r', '\n');
RichieHindle
  • 272,464
  • 47
  • 358
  • 399
  • 10
    Take note of the params keyword in the declaration of TrimEnd, it let's you pass multiple instances of a character instead of the array. http://msdn.microsoft.com/en-us/library/w5zay9db(VS.71).aspx – JP Alioto May 16 '09 at 18:59
  • 4
    How about this: s = s.TrimEnd(System.Environment.NewLine.ToCharArray()); – Ε Г И І И О Oct 06 '12 at 21:11
  • 4
    I've been writing c# since v1.0 came out (10 years ago). Now you tell me about TrimEnd. Doh! – s15199d Dec 28 '12 at 20:05
  • 7
    Just out of interest, all you really need is `s = s.TrimEnd()` - as the docs say: _If trimChars is null or an empty array, Unicode white-space characters are removed instead._ - see [String.TrimEnd](http://msdn.microsoft.com/en-gb/library/system.string.trimend.aspx) – Stuart Wood Mar 12 '13 at 12:37
  • @StuartWood: ...which is not what Avik asked for. He asked specifically for `'\r'` and `'\n'` and nothing else, not the space character `' '` for instance. – RichieHindle Mar 12 '13 at 13:11
  • http://stackoverflow.com/questions/4973524/how-to-remove-extra-returns-and-spaces-in-a-string-by-regex/4974031#4974031 – Allen Jan 29 '15 at 15:55
  • Here is the correct answer: https://stackoverflow.com/a/35890472/229930 – Dean Kuga Aug 13 '21 at 16:54
34

This should work ...

var tst = "12345\n\n\r\n\r\r";
var res = tst.TrimEnd( '\r', '\n' );
JP Alioto
  • 44,864
  • 6
  • 88
  • 112
21
String temp = s.Replace("\r\n","").Trim();

s being the original string. (Note capitals)

dashnick
  • 2,020
  • 19
  • 34
Crash893
  • 11,428
  • 21
  • 88
  • 123
20

If you are using multiple platforms you are safer using this method.

value.TrimEnd(System.Environment.NewLine.ToCharArray());

It will account for different newline and carriage-return characters.

Alex Wiese
  • 8,142
  • 6
  • 42
  • 71
  • JP's method -- `tst.TrimEnd( '\r', '\n' )` -- is reasonably "safe" in practice since major EOLs are [currently] just different combos of `\r` and `\n`, but alexw's is the "right" answer. *Let the CLR tell you what chars are in this platform's newline.* [EOL hasn't always been combos of 0Ds and 0As](http://en.wikipedia.org/wiki/Newline#Representations) – ruffin Apr 26 '14 at 15:23
  • I used to use `Environment.NewLine` but it didn't seem to handle instances where `\r` was present without `\n`. `TrimEnd('r','\n')` seems to be more reliable in this case. – ᴍᴀᴛᴛ ʙᴀᴋᴇʀ May 28 '14 at 09:09
  • 3
    It could be that this is actually a cross-platform issue, and dec needs to specifically remove both \r \n, irrespective of what the system environment says. – Andrew Hill Apr 20 '15 at 00:20
10
s.TrimEnd();

The above is all I needed to remove '\r\n' from the end of my string.

The upvoted answer seems wrong to me. Firstly, it didn't work when I tried, secondly, if it did work I would expect that s.TrimEnd('\r', '\n') would only remove either a '\r' or a '\n', so I'd have to run it over my string twice - once for when '\n' was at the end and the second time for when '\r' was at the end (now that the '\n' was removed).

martinp999
  • 419
  • 6
  • 10
  • 1
    This does work to remove \r and \n but will also remove all white space, so in some cases may go too far. Note the doc for this method: " If trimChars is null or an empty array, Unicode white-space characters are removed instead." – Craig Oct 22 '20 at 12:21
4

For us VBers:

TrimEnd(New Char() {ControlChars.Cr, ControlChars.Lf})
Simon
  • 6,062
  • 13
  • 60
  • 97
4
string k = "This is my\r\nugly string. I want\r\nto change this. Please \r\n help!";
k = System.Text.RegularExpressions.Regex.Replace(k, @"\r\n+", " ");
vnRock
  • 137
  • 3
4

If there's always a single CRLF, then:

myString = myString.Substring(0, myString.Length - 2);

If it may or may not have it, then:

Regex re = new Regex("\r\n$");
re.Replace(myString, "");

Both of these (by design), will remove at most a single CRLF. Cache the regex for performance.

Matthew Flaschen
  • 278,309
  • 50
  • 514
  • 539
3

This was too easy -- for me I'm filtering out certain email items. I'm writing my own custom email junk filter. With \r and/or \n in the string it was wiping out all items instead of filtering.

So, I just did filter = filter.Remove('\n') and filter = filter.Remove('\r'). I'm making my filter such that an end user can use Notepad to directly edit the file so there's no telling where these characters might embed themselves -- could be other than at the start or end of the string. So removing them all does it.

The other entries all work but Remove might be the easiest?

I learned quite a bit more about Regex from this post -- pretty cool work with its use here.

user1585204
  • 827
  • 1
  • 10
  • 14
2

I use lots of erasing level

String donen = "lots of stupid whitespaces and new lines and others..."

//Remove multilines
donen = Regex.Replace(donen, @"^\s+$[\r\n]*", "", RegexOptions.Multiline);
//remove multi whitespaces
RegexOptions options = RegexOptions.None;
Regex regex = new Regex("[ ]{2,}", options);
donen = regex.Replace(donen, " ");
//remove tabs
char tab = '\u0009';
donen = donen.Replace(tab.ToString(), "");
//remove endoffile newlines
donen = donen.TrimEnd('\r', '\n');
//to be sure erase new lines again from another perspective
donen.Replace(Environment.NewLine, "");

and now we have a clean one row

matasoy
  • 659
  • 1
  • 6
  • 7
2

This is what I got to work for me.

s.Replace("\r","").Replace("\n","")
Paul Roub
  • 36,322
  • 27
  • 84
  • 93
0
varName.replace(/[\r\n]/mg, '')                                              
John Conde
  • 217,595
  • 99
  • 455
  • 496
Pat
  • 627
  • 1
  • 9
  • 24
0

If you use the nuget IvanStoychev.Useful.String.Extensions you can do:

s = s.TrimEnd(Environment.Newline);

It adds an overload of TrimEnd that takes a string.

Tessaract
  • 1,047
  • 7
  • 24