How to insert newline in string literal?

前端 未结 12 742
没有蜡笔的小新
没有蜡笔的小新 2020-12-07 09:07

In .NET I can provide both \\r or \\n string literals, but there is a way to insert something like \"new line\" special character like Enviro

相关标签:
12条回答
  • 2020-12-07 09:41

    Here, Environment.NewLine doesn't worked.

    I put a "<br/>" in a string and worked.

    Ex:

    ltrYourLiteral.Text = "First line.<br/>Second Line.";

    0 讨论(0)
  • 2020-12-07 09:43
    static class MyClass
    {
       public const string NewLine="\n";
    }
    
    string x = "first line" + MyClass.NewLine + "second line"
    
    0 讨论(0)
  • 2020-12-07 09:45
    string myText =
        @"<div class=""firstLine""></div>
          <div class=""secondLine""></div>
          <div class=""thirdLine""></div>";
    

    that's not it:

    string myText =
    @"<div class=\"firstLine\"></div>
      <div class=\"secondLine\"></div>
      <div class=\"thirdLine\"></div>";
    
    0 讨论(0)
  • 2020-12-07 09:51
    var sb = new StringBuilder();
    sb.Append(first);
    sb.AppendLine(); // which is equal to Append(Environment.NewLine);
    sb.Append(second);
    return sb.ToString();
    
    0 讨论(0)
  • 2020-12-07 09:53

    Well, simple options are:

    • string.Format:

      string x = string.Format("first line{0}second line", Environment.NewLine);
      
    • String concatenation:

      string x = "first line" + Environment.NewLine + "second line";
      
    • String interpolation (in C#6 and above):

      string x = $"first line{Environment.NewLine}second line";
      

    You could also use \n everywhere, and replace:

    string x = "first line\nsecond line\nthird line".Replace("\n",
                                                             Environment.NewLine);
    

    Note that you can't make this a string constant, because the value of Environment.NewLine will only be available at execution time.

    0 讨论(0)
  • 2020-12-07 09:53

    If you want a const string that contains Environment.NewLine in it you can do something like this:

    const string stringWithNewLine =
    @"first line
    second line
    third line";
    

    EDIT

    Since this is in a const string it is done in compile time therefore it is the compiler's interpretation of a newline. I can't seem to find a reference explaining this behavior but, I can prove it works as intended. I compiled this code on both Windows and Ubuntu (with Mono) then disassembled and these are the results:

    Disassemble on Windows Disassemble on Ubuntu

    As you can see, in Windows newlines are interpreted as \r\n and on Ubuntu as \n

    0 讨论(0)
提交回复
热议问题