stringbuilder中的换行符

use*_*364 85 c# stringbuilder

如何追加新行(\n\r)字符StringBuilder

Adr*_*der 121

我会使用Environment.NewLine属性

就像是

StringBuilder sb = new StringBuilder();
sb.AppendFormat("Foo{0}Bar", Environment.NewLine);
string s = sb.ToString();
Run Code Online (Sandbox Code Playgroud)

要么

StringBuilder sb = new StringBuilder();
sb.Append("Foo");
sb.Append("Foo2");
sb.Append(Environment.NewLine);
sb.Append("Bar");
string s = sb.ToString();
Run Code Online (Sandbox Code Playgroud)

编辑:

如果您希望在每次追加后都有一个新行,您可以查看@Ben Voigt的答案.

  • Stringbuilder.AppendLine()与sb.Append(Environment.NewLine)做同样的事情; 它也更整洁我想说(http://msdn.microsoft.com/en-us/library/ebk18257.aspx) (4认同)
  • 请注意,unix系统上的Environment.NewLine不是"\ r \n",因此如果要实现指定为"\ r \n"的内容,则必须在代码中编写它而不是调用AppendLine. (3认同)
  • 可以将Append和AppendLine混合使用,以在所需的位置获得新行,而不是在每个Append之后。此外,我链接到AppendLine的零参数版本,该版本仅附加换行序列。 (2认同)
  • AppendLine 比此方法更简单。 (2认同)

Fit*_*aki 22

另外,使用StringBuilder.AppendLine方法.


Lij*_*ijo 6

使用 StringBuilder 的 append line 内置函数:

StringBuilder sb = new StringBuilder();
sb.AppendLine("First line");
sb.AppendLine("Second line");
sb.AppendLine("Third line");
Run Code Online (Sandbox Code Playgroud)

输出

StringBuilder sb = new StringBuilder();
sb.AppendLine("First line");
sb.AppendLine("Second line");
sb.AppendLine("Third line");
Run Code Online (Sandbox Code Playgroud)


Ker*_*ang 5

它将\n改为在 Linux 中追加\r\n