How to remove new line characters from a string?

Ashish Ashu picture Ashish Ashu · Nov 10, 2010 · Viewed 267.4k times · Source

I have a string in the following format

string s = "This is a Test String.\n   This is a next line.\t This is a tab.\n'

I want to remove all the occurrences of \n and \r from the string above.

I have tried string s = s.Trim(new char[] {'\n', '\r'}); but it didn't help.

Answer

Kirk picture Kirk · Nov 10, 2010

I like to use regular expressions. In this case you could do:

string replacement = Regex.Replace(s, @"\t|\n|\r", "");

Regular expressions aren't as popular in the .NET world as they are in the dynamic languages, but they provide a lot of power to manipulate strings.