简体   繁体   中英

newline character in c# string

I have some html code in a C# string. If I look with the Text Visualizer of Visual Studio I can see it has numerous newlines in it. However, after i apply this code

string modifiedString = originalString.Replace(Environment.NewLine, "<br />");

and then I look with the Text Visualizer at modifiedString I can see it doesn't have anymore newlines except for 3 places. Are there any other character types than resemble newline and I am missing?

They might be just a \\r or a \\n . I just checked and the text visualizer in VS 2010 displays both as newlines as well as \\r\\n .

This string

string test = "blah\r\nblah\rblah\nblah";

Shows up as

blah
blah
blah
blah

in the text visualizer.

So you could try

string modifiedString = originalString
    .Replace(Environment.NewLine, "<br />")
    .Replace("\r", "<br />")
    .Replace("\n", "<br />");

A great way of handling this is with regular expressions.

string modifiedString = Regex.Replace(originalString, @"(\r\n)|\n|\r", "<br/>");


This will replace any of the 3 legal types of newline with the html tag.

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