简体   繁体   中英

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"

这读起来更好:

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

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, ie

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

您是否将返回值设置回变量?

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

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

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

尝试这个:

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

You better try this.

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

Hope this work.

Try this.

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

It's work for me ;)

Sometimes you cannot replace new lines from JSON strings. The following code will eliminate all the chances.

json = json.Replace(Environment.NewLine, "").Replace("\r\n", "").Replace("\r", "").Replace("\n", "").Replace("\\r", "").Replace("\\n", "");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM