Generating an indented string for a single line of text

随声附和 提交于 2019-12-05 11:43:58

You can create your indention with this:

var indent = new string(' ', indentLevel * IndentSize);

IndentSize would be a constant with value 4 or 8.

eandersson

I would probably do something like this to add Indent.

public static string Indent(int count)
{
    return "".PadLeft(count);
}

To use it you can do the following:

Indent(4) + "My Random Text"

In your application you could simply do:

s.Write(Indent(indentLevel));

or

s.Write("".PadLeft(indentLevel));

It comes in the box!

Use System.CodeDom.Compiler.IndentedTextWriter.

If you want to indent every line of a string you can use this extention.

public static class StringExtensions
{
    public static string Indent(this string value, int size)
    {
        var strArray = value.Split('\n');
        var sb = new StringBuilder();
        foreach (var s in strArray)
            sb.Append(new string(' ', size)).Append(s);
        return sb.ToString();
    }
}

Use it like this :

MyString.Indent(4);

You can use this generic string extension method (it's performance and memory optimal). You can keep it inside a central 'core' project reference by your main application project(s), then whenever you want to get the indented version of any string, it's just:

myString.Indent(n)

(where 'n' is the indent level)

private const byte _indentSize = 4;

public static string Indent(this string originalString, int indentLevel)
{
    StringBuilder indentedString = new StringBuilder();
    indentedString.Append("".PadLeft(indentLevel * _indentSize));
    indentedString.Append(originalString);
    return indentedString.ToString();
}

yet another way:

int indentLevel = 4;
string myText = "This string will become indented";

string res = String.Format("{0," + indentLevel + "}{1}", String.Empty, myText);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!