如何插入新行的字符串?字符串

2023-09-02 01:53:05 作者:淑女路线我不走

在.NET中我可以同时提供 r ñ字符串,但有一个办法插入 像新线特殊字符,如 Environment.NewLine 静态属性?

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 Environment.NewLine static property?

推荐答案

好了,简单的选项有:

的String.Format

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

字符串连接:

String concatenation:

string x = "first line" + Environment.NewLine + "second line";

路线插值(在C#6及以上):

String interpolation (in C#6 and above):

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

您也可使用 n随处可见,并替换:

You could also use n everywhere, and replace:

string x = "first linensecond linenthird line".Replace("n",
                                                         Environment.NewLine);

请注意,你不能让这个字符串的恒的,因为 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.