Slorthe
Slorthe

Reputation: 121

How do I remove \r\n from string in C#?

I am trying to figure out an easy way remove \r\n from a string.

Example: text = "this.is.a.string.\r\nthis.is.a.string\r\n"

I tried:

text.Replace("\r\n", "") and text.Replace("\r\n", string.Empty), but it doesn't work. \r\n is still in the string...

The result should be: "this.is.a.string.this.is.a.string"

Upvotes: 7

Views: 55214

Answers (7)

Luke Hutton
Luke Hutton

Reputation: 10722

This reads better:

text = text.Replace(System.Environment.NewLine, string.Empty);

Upvotes: 34

Ramya Prakash Rout
Ramya Prakash Rout

Reputation: 141

Strings in .NET are immutable and so you cannot change an existing string - you can only create a new one. The Replace method returns the modified result, i.e.

text = text.Replace(System.Environment.NewLine, string.Empty);
text = JObject.Parse(text);

Upvotes: 5

raghu sathvara
raghu sathvara

Reputation: 196

Try this:

text = text.Replace(System.Environment.NewLine, "");

Upvotes: 1

ps2goat
ps2goat

Reputation: 8475

Are you setting the return value back to the variable?

text = text.Replace(@"\r\n", "");

Upvotes: 2

Alex
Alex

Reputation: 266

It returns a value. You need to say text = ...

text = text.Replace(@"\r\n", "");

Upvotes: 2

Mardika Reza Setiawan
Mardika Reza Setiawan

Reputation: 19

Try this.

text = text .Replace("\\r\\n", "");

It's work for me ;)

Upvotes: 0

Zin Win Htet
Zin Win Htet

Reputation: 2563

You better try this.

text = text.Replace("\r\n", ""); 

Hope this work.

Upvotes: -1

Related Questions