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.
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 .
StringBuilder stringBuilder = new StringBuilder(); foreach (string field in fields) { stringBuilder. Append(field + "\t"). Append("\t"); } stringBuilder.
The default capacity of a StringBuilder object is 16 characters, and its default maximum capacity is Int32. MaxValue.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With