缩进多行文本

Mar*_*nze 9 c# string indentation

我需要缩进多行文本(与单行文本的这个问题形成对比).

让我们说这是我的输入文字:

First line
  Second line
Last line
Run Code Online (Sandbox Code Playgroud)

我需要的是这个结果:

    First line
      Second line
    Last line
Run Code Online (Sandbox Code Playgroud)

注意每行中的缩进.

这是我到目前为止:

var textToIndent = @"First line
  Second line
Last line.";
var splittedText = textToIndent.Split(new string[] {Environment.NewLine}, StringSplitOptions.None);
var indentAmount = 4;
var indent = new string(' ', indentAmount);
var sb = new StringBuilder();
foreach (var line in splittedText) {
    sb.Append(indent);
    sb.AppendLine(line);
}
var result = sb.ToString();
Run Code Online (Sandbox Code Playgroud)

有更安全/更简单的方法吗?

我关注的是split方法,如果转移来自Linux,Mac或Windows的文本,并且新行可能无法在目标计算机中正确拆分,则可能会很棘手.

Who*_*ich 17

既然你要缩进所有的行,那么做如下的事情:

var result = indent + textToIndent.Replace("\n", "\n" + indent);
Run Code Online (Sandbox Code Playgroud)

哪个应涵盖Windows\r \n和Unix \n行尾.

  • +1.仅仅为了完整性,一些模糊/遗留系统使用其他"换行"组合:[换行表示](http://en.wikipedia.org/wiki/Newline#Representations). (6认同)
  • 这很好,谢谢!而且我不确定"\n",但实际上认为如果你只需要处理Windows和Unix,"\n"可能会更好,因为这将解析其他系统发送的字符串.否则,Windows环境将不会取代Unix换行符.但是如果你需要支持Mac OS 9(或其他),我认为Environment.NewLine会更好用. (6认同)