如何添加一定数量的空格来StringBuilder的? [英] how to add certain number of whitespaces to StringBuilder?
问题描述
我怎么可以添加一定数量的空格(1到100之间),以StringBuilder的?
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 */);
什么是理想的解决方案? 为
循环是丑陋的。我还可以创建数组,其中空格[I]
包含正好包含 I
空格字符串,但是这将是很长硬编码的数组。
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.
推荐答案
您可以使用的 StringBuilder.Append(CHAR,INT)
方法,它重复指定的Unicode字符的指定次数:
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));
这将追加你的时间
字符串,然后通过 100 - time.Length
空格
This would append your time
string, followed by 100 - time.Length
spaces.
修改:如果你只使用的StringBuilder
来构造填充时间,那么你就可以做掉它干脆:
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);
这篇关于如何添加一定数量的空格来StringBuilder的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!