问题
What is the best way to generate an indented line from space characters. I mean something similar to this:
string indent = String.Join(" ", new String[indentlevel]);
s.Write(indent + "My line of text");
回答1:
You can create your indention with this:
var indent = new string(' ', indentLevel * IndentSize);
IndentSize
would be a constant with value 4 or 8.
回答2:
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));
回答3:
It comes in the box!
Use System.CodeDom.Compiler.IndentedTextWriter.
回答4:
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);
回答5:
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();
}
回答6:
yet another way:
int indentLevel = 4;
string myText = "This string will become indented";
string res = String.Format("{0," + indentLevel + "}{1}", String.Empty, myText);
来源:https://stackoverflow.com/questions/15529672/generating-an-indented-string-for-a-single-line-of-text