缩进多行文本

时间:2014-04-05 01:14:49

标签: c# string indentation

我需要缩进多行文本(与this question for a single line of text相反)。

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

First line
  Second line
Last line

我需要的是这个结果:

    First line
      Second line
    Last line

注意每行的缩进。

这是我到目前为止所做的:

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();

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

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

5 个答案:

答案 0 :(得分:16)

由于您要缩进所有行,请执行以下操作:

var result = indent + textToIndent.Replace("\n", "\n" + indent);

这应涵盖Windows \ r \ n和Unix \ n行尾。

答案 1 :(得分:4)

只需用换行符+缩进替换你的换行符:

var indentAmount = 4;
var indent = new string(' ', indentAmount);
textToIndent = indent + textToIndent.Replace(Environment.NewLine, Environment.NewLine + indent);

答案 2 :(得分:1)

与此处发布的其他解决方案相比,以下解决方案可能看起来比较冗长;但是它有一些明显的优点:

  • 它将完全保留输入字符串中的行分隔符/终止符。
  • 它不会在字符串的末尾添加多余的缩进字符。
  • 可能运行得更快,因为它仅使用非常原始的操作(字符比较和复制;没有子字符串搜索,也没有正则表达式)。 (但这只是我的期望;我尚未实际测量。)
static string Indent(this string str, int count = 1, char indentChar = ' ')
{
    var indented = new StringBuilder();
    var i = 0;
    while (i < str.Length)
    {
        indented.Append(indentChar, count);
        var j = str.IndexOf('\n', i + 1);
        if (j > i)
        {
            indented.Append(str, i, j - i + 1);
            i = j + 1;
        }
        else
        {
            break;
        }
    }
    indented.Append(str, i, str.Length - i);
    return indented.ToString();
}

答案 3 :(得分:0)

Stakx的答案使我开始考虑不添加多余的缩进字符。而且我认为最好不仅在字符串的末尾而且在字符串的中部和开头都避免使用这些字符(当那一行都包含这些字符时)。

仅当新行不跟在另一行之后时,我才使用Regex替换新行,而另一行Regex则避免在字符串以新行开头的情况下添加第一个缩进:

const popAction = StackActions.pop({
  n: 1, // number of screens to pop back by.
});

this.props.navigation.dispatch(popAction);

我在方法之外创建了Regex s ,以加快多次替换的速度。

可以在以下位置测试此解决方案:https://ideone.com/9yu5Ih

答案 4 :(得分:0)

如果您需要将通用缩进添加到多行字符串的字符串扩展名,可以使用:

public static string Indent(this string input, string indent)
{
    return string.Join(Environment.NewLine, input.Split(Environment.NewLine).Select(item => string.IsNullOrEmpty(item.Trim()) ? item : indent + item));
}

此扩展名跳过空行。 如果您知道linq,则此解决方案非常容易理解,如果需要使它适应不同的范围,则调试和更改也更简单。