如何向StringBuilder添加一定数量的空格?

如何在StringBuilder中添加一定数量(1到100之间)的空格?

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

什么是“理想”的解决方案? for循环是丑陋的。 我也可以创建数组,其中whitespaces[i]包含完全包含空格的字符串,但这将是相当长的硬编码数组。

您可以使用StringBuilder.Append(char,int)方法,该方法重复指定的Unicode字符指定的次数:

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

更好的是,将两个附加组合成一个操作:

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

这将附加你的time字符串,然后是100 - time.Length空格。

编辑 :如果您只使用StringBuilder构建填充时间,那么您可以完全取消它:

 string nextLine = time.PadRight(100); 

您可以使用带有charint的StringBuilder.Append重载 :

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

使用PadLeft –

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