How to insert newline in string literal?

前端 未结 12 779
没有蜡笔的小新
没有蜡笔的小新 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: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.

提交回复
热议问题