8

How can I add certain number (between 1 and 100) of whitespaces to StringBuilder?

StringBuilder nextLine = new StringBuilder();
string time = Util.CurrentTime;
nextLine.Append(time);
nextLine.Append(/* add (100 - time.Length) whitespaces */);

What would be "ideal" solution? for loop is ugly. I can also create array where whitespaces[i] contains string which contains exactly i whitespaces, but that would be pretty long hardcoded array.

4

3 回答 3

18

You can use the StringBuilder.Append(char,int) method, which repeats the specified Unicode character a specified number of times:

nextLine.Append(time);
nextLine.Append(' ', 100 - time.Length);

Better yet, combine both appends into a single operation:

nextLine.Append(time.PadRight(100));

This would append your time string, followed by 100 - time.Length spaces.

Edit: If you’re only using the StringBuilder to construct the padded time, then you can do away with it altogether:

string nextLine = time.PadRight(100);
于 2012-06-03T11:47:40.610 回答
6

You can use the StringBuilder.Append overload that takes a char and an int:

nextLine.Append(' ', 100 - time.Length);
于 2012-06-03T11:52:36.307 回答
2

Use PadLeft -

nextLine.Append(String.Empty.PadLeft(' ', 100 - time.Length));
于 2012-06-03T11:48:09.060 回答