如何向 StringBuilder 添加一定数量(1 到 100 之间)的空格?
StringBuilder nextLine = new StringBuilder();
string time = Util.CurrentTime;
nextLine.Append(time);
nextLine.Append(/* add (100 - time.Length) whitespaces */);
什么是“理想”的解决方案?for
循环很丑陋。我还可以在其中创建数组whitespaces[i]
包含恰好包含的字符串i
空格,但这将是相当长的硬编码数组。
您可以使用StringBuilder.Append(char,int) http://msdn.microsoft.com/en-us/library/yxyxbz2e.aspx方法,该方法将指定的 Unicode 字符重复指定的次数:
nextLine.Append(time);
nextLine.Append(' ', 100 - time.Length);
更好的是,将两个追加合并到一个操作中:
nextLine.Append(time.PadRight(100));
这将附加您的time
字符串,后跟100 - time.Length
spaces.
Edit:如果您只使用StringBuilder
构建填充时间,那么你可以完全取消它:
string nextLine = time.PadRight(100);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)