Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to add certain number of whitespaces to StringBuilder?

Tags:

c#

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.

like image 933
Oleg Vazhnev Avatar asked Jun 03 '12 11:06

Oleg Vazhnev


People also ask

How do you add a space in a string buffer?

StringJoiner is used to construct a sequence of characters separated by a delimiter and optionally starting with a supplied prefix and ending with a supplied suffix. StringJoiner joiner = new StringJoiner(" "); // Use 'space' as the delimiter joiner. add("watch") // watch . add("on") // watch on .

How do you add a tab character in StringBuilder?

StringBuilder stringBuilder = new StringBuilder(); foreach (string field in fields) { stringBuilder. Append(field + "\t"). Append("\t"); } stringBuilder.

How many characters can StringBuilder hold?

The default capacity of a StringBuilder object is 16 characters, and its default maximum capacity is Int32. MaxValue.


1 Answers

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);
like image 194
Douglas Avatar answered Sep 22 '22 09:09

Douglas