[c#] Removing carriage return and new-line from the end of a string in c#

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

This question is related to c# string newline carriage-return

The answer is


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).


This should work ...

var tst = "12345\n\n\r\n\r\r";
var res = tst.TrimEnd( '\r', '\n' );

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.


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+", " ");

This is what I got to work for me.

s.Replace("\r","").Replace("\n","")

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.


String temp = s.Replace("\r\n","").Trim();

s being the original string. (Note capitals)


For us VBers:

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

varName.replace(/[\r\n]/mg, '')                                              

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


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.


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to newline

How can I insert a line break into a <Text> component in React Native? Print "\n" or newline characters as part of the output on terminal Using tr to replace newline with space How to write one new line in Bitbucket markdown? Line break in SSRS expression How to insert a new line in Linux shell script? Replace CRLF using powershell How to write new line character to a file in Java What is the newline character in the C language: \r or \n? How to print values separated by spaces instead of new lines in Python 2.7

Examples related to carriage-return

Create Carriage Return in PHP String? What is the difference between a "line feed" and a "carriage return"? How can I insert new line/carriage returns into an element.textContent? What are the differences between char literals '\n' and '\r' in Java? What's the Use of '\r' escape sequence? Carriage return and Line feed... Are both required in C#? Find and replace - Add carriage return OR Newline In C#, what's the difference between \n and \r\n? See line breaks and carriage returns in editor What are carriage return, linefeed, and form feed?