newline character in c# string

前端 未结 2 941
北恋
北恋 2021-01-06 00:58

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

相关标签:
2条回答
  • 2021-01-06 01:17

    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.

    0 讨论(0)
  • 2021-01-06 01:23

    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 />");
    
    0 讨论(0)
提交回复
热议问题