为单行文本生成缩进字符串

Roa*_*ich 5 c# string indentation

从空格字符生成缩进行的最佳方法是什么?我的意思是这样的:

    string indent = String.Join("    ", new String[indentlevel]);
    s.Write(indent + "My line of text");
Run Code Online (Sandbox Code Playgroud)

Dan*_*rth 18

您可以使用以下方法创建缩进:

var indent = new string(' ', indentLevel * IndentSize);
Run Code Online (Sandbox Code Playgroud)

IndentSize 将是一个值为4或8的常数.


ean*_*son 8

我可能会做这样的事情来补充Indent.

public static string Indent(int count)
{
    return "".PadLeft(count);
}
Run Code Online (Sandbox Code Playgroud)

要使用它,您可以执行以下操作:

Indent(4) + "My Random Text"
Run Code Online (Sandbox Code Playgroud)

在您的应用程序中,您可以简单地执

s.Write(Indent(indentLevel));
Run Code Online (Sandbox Code Playgroud)

要么

s.Write("".PadLeft(indentLevel));
Run Code Online (Sandbox Code Playgroud)


lep*_*pie 5

它出现在盒子里!

使用System.CodeDom.Compiler.IndentedTextWriter.

  • 这是通用的:)只提供任何`TextWriter`,例如`StringWriter`或`Console.Out` (3认同)