views:

6735

answers:

5

Guys how do I remove the carriage return character(\r) and the new line character(\n) from the end of a string?

+11  A: 

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
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
Good tip - thanks! I didn't know about that.
RichieHindle
+4  A: 

This should work ...

var tst = "12345\n\n\r\n\r\r";
var res = tst.TrimEnd( '\r', '\n' );
JP Alioto
+1  A: 

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
A: 

String temp = s.replace("\r\n","").trim();

S being the oringnal string

Crash893
That will also: 1) Remove \r\n from the middle of the string, 2) Remove any whitespace characters from the start of the string, and 3) remove any whitespace characters from the end of the string.
RichieHindle
True, I assumed only one /r/n at the end. It wasn't mentioned in the orginal post. I'm not sure that warrents a -1 vote
Crash893
A: 

For us VBers:

TrimEnd(New Char() {ControlChars.Cr, ControlChars.Lf})
Simon