Reputation: 14256
I have an instance of StringBuilder
in my C# application wherein I would like certain lines to be padded with a varying number of spaces depending on the context. My usage is very simple:
StringBuilder MyStringBuilder = new StringBuilder();
MyStringBuilder.AppendFormat("{0:" + this._padding + "}"); // <-- Exception thrown here
MyStringBuilder.AppendLine("My data.");
If this._padding==10
, the resulting output should look something like this:
My data.
How can I pad my strings without resorting to using a for loop? Thanks.
ADDITIONAL INFO
Exception: "Index (zero based) must be greater than or equal to zero and less than the size of the argument list."
Upvotes: 1
Views: 2398
Reputation: 273189
Try
// AppendFormat("{0:" + this._padding + "}");
AppendFormat("{0:" + this._padding + "}", "");
A place-holder is holding a place for something.
Exception: "Index (zero based) must be greater than or equal to zero and less than the size of the argument list."
0
is greater than or equal to zero but it in this case it was not less than the size of the argument list (0
as well).
Upvotes: 1
Reputation: 4384
A lame way of doing it, but should work
for(int i=0; i <this._padding; i++)
{
MyStringBuilder.AppendFormat("{0}"," ");
}
_padding needs to be an int
Upvotes: -1
Reputation: 838096
{0,10}
, not {0:10}
.Try this:
MyStringBuilder.AppendFormat("{0," + this._padding + "}", "My Data");
There is also a string.PadLeft
method that you could use.
MyStringBuilder.Append("My Data".PadLeft(this._padding));
Upvotes: 4
Reputation: 85645
That seems a strange way of doing:
sb.Append(' ', this._padding).AppendLine("My Data");
Upvotes: 2
Reputation: 28688
You cannot simply write something like MyStringBuilder.AppendFormat("{0}");
You must give the variable to be formatted by the format string, like MyStringBuilder.AppendFormat("{0}", "My data");
Upvotes: 1
Reputation: 6090
You can use IEnumerable.Repeat to generate arbitrary numbers of the same string/char.
http://msdn.microsoft.com/en-us/library/bb348899.aspx
Upvotes: 0
Reputation: 160852
AppendFormat()
expects the data to format as additional argument:
MyStringBuilder.AppendFormat("{0:" + this._padding + "}", "My data.");
Upvotes: 3