Cap*_*mic 147 .net c# line-breaks
在.NET中,我可以提供两者\r
或\n
字符串文字,但有一种方法可以插入像"new line"这样的特殊字符,比如Environment.NewLine
静态属性?
Jon*_*eet 305
嗯,简单的选择是:
string.Format
:
string x = string.Format("first line{0}second line", Environment.NewLine);
Run Code Online (Sandbox Code Playgroud)字符串连接:
string x = "first line" + Environment.NewLine + "second line";
Run Code Online (Sandbox Code Playgroud)字符串插值(在C#6及以上版本中):
string x = $"first line{Environment.NewLine}second line";
Run Code Online (Sandbox Code Playgroud)您也可以在任何地方使用\n,并替换:
string x = "first line\nsecond line\nthird line".Replace("\n",
Environment.NewLine);
Run Code Online (Sandbox Code Playgroud)
请注意,您不能将此字符串设为常量,因为该值Environment.NewLine
仅在执行时可用.
Tal*_*ome 32
如果你想要一个包含Environment.NewLine的const字符串,你可以这样做:
const string stringWithNewLine =
@"first line
second line
third line";
Run Code Online (Sandbox Code Playgroud)
由于这是一个const字符串,它在编译时完成,因此它是编译器对换行符的解释.我似乎找不到解释这种行为的参考,但我可以证明它按预期工作.我在Windows和Ubuntu(使用Mono)上编译了这段代码,然后进行了反汇编,结果如下:
如您所见,在Windows中,换行符被解释为\ r \n,在Ubuntu上被解释为\n
aba*_*hev 13
var sb = new StringBuilder();
sb.Append(first);
sb.AppendLine(); // which is equal to Append(Environment.NewLine);
sb.Append(second);
return sb.ToString();
Run Code Online (Sandbox Code Playgroud)