How to remove new line characters from a string?

C#.Net

C# Problem Overview


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.

C# Solutions


Solution 1 - C#

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.

Solution 2 - C#

You want to use String.Replace to remove a character.

s = s.Replace("\n", String.Empty);
s = s.Replace("\r", String.Empty);
s = s.Replace("\t", String.Empty);

Note that String.Trim(params char[] trimChars) only removes leading and trailing characters in trimChars from the instance invoked on.

You could make an extension method, which avoids the performance problems of the above of making lots of temporary strings:

static string RemoveChars(this string s, params char[] removeChars) {
    Contract.Requires<ArgumentNullException>(s != null);
    Contract.Requires<ArgumentNullException>(removeChars != null);
    var sb = new StringBuilder(s.Length);
    foreach(char c in s) { 
        if(!removeChars.Contains(c)) {
            sb.Append(c);
        }
    }
    return sb.ToString();
}

Solution 3 - C#

I know this is an old post, however I thought I'd share the method I use to remove new line characters.

s.Replace(Environment.NewLine, "");

References:

MSDN String.Replace Method and MSDN Environment.NewLine Property

Solution 4 - C#

If speed and low memory usage are important, do something like this:

var sb = new StringBuilder(s.Length);

foreach (char i in s)
    if (i != '\n' && i != '\r' && i != '\t')
        sb.Append(i);

s = sb.ToString();

Solution 5 - C#

just do that

s = s.Replace("\n", String.Empty).Replace("\t", String.Empty).Replace("\r", String.Empty);

Solution 6 - C#

A LINQ approach:

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

string s1 = String.Join("", s.Where(c => c != '\n' && c != '\r' && c != '\t'));

Solution 7 - C#

The right choice really depends on how big the input string is and what the perforce and memory requirement are, but I would use a regular expression like

string result = Regex.Replace(s, @"\r\n?|\n|\t", String.Empty);

Or if we need to apply the same replacement multiple times, it is better to use a compiled version for the Regex like

var regex = new Regex(@"\r\n?|\n|\t", RegexOptions.Compiled); 
string result = regex.Replace(s, String.Empty);

NOTE: different scenarios requite different approaches to achieve the best performance and the minimum memory consumption

Solution 8 - C#

Well... I would like you to understand more specific areas of space. \t is actually assorted as a horizontal space, not a vertical space. (test out inserting \t in Notepad)

If you use Java, simply use \v. See the reference below.

> \h - A horizontal whitespace character: > > [\t\xA0\u1680\u180e\u2000-\u200a\u202f\u205f\u3000] > > \v - A vertical whitespace character: > > [\n\x0B\f\r\x85\u2028\u2029]

But I am aware that you use .NET. So my answer to replacing every vertical space is..

string replacement = Regex.Replace(s, @"[\n\u000B\u000C\r\u0085\u2028\u2029]", "");

Solution 9 - C#

string remove = Regex.Replace(txtsp.Value).ToUpper(), @"\t|\n|\r", "");

Solution 10 - C#

You can use Trim if you want to remove from start and end.

string stringWithoutNewLine = "\n\nHello\n\n".Trim();

Solution 11 - C#

FYI,

Trim() does that already.

The following LINQPad sample:

void Main()
{
	var s = " \rsdsdsdsd\nsadasdasd\r\n ";
	s.Length.Dump();
	s.Trim().Length.Dump();
}

Outputs:

23
18

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAshish AshuView Question on Stackoverflow
Solution 1 - C#KirkView Answer on Stackoverflow
Solution 2 - C#jasonView Answer on Stackoverflow
Solution 3 - C#ᴍᴀᴛᴛ ʙᴀᴋᴇʀView Answer on Stackoverflow
Solution 4 - C#cdhowieView Answer on Stackoverflow
Solution 5 - C#Mahmoud ElMansyView Answer on Stackoverflow
Solution 6 - C#w.bView Answer on Stackoverflow
Solution 7 - C#kalitsovView Answer on Stackoverflow
Solution 8 - C#Kang AndrewView Answer on Stackoverflow
Solution 9 - C#CodeView Answer on Stackoverflow
Solution 10 - C#Ankit AryaView Answer on Stackoverflow
Solution 11 - C#lnaieView Answer on Stackoverflow