具有可变空间对齐的C#字符串格式

具有可变空间对齐的C#字符串格式,c#,string-formatting,C#,String Formatting,我想做一些像 String.Format("Completed {0:9} of ",0) + xlsx.totalCount.ToString(); 除了不硬编码9之外,我希望对齐方式是xlsx.totalCount。有什么想法吗?字符串不必是编译时常量,您可以在运行时构建字符串(使用StringBuilder、运算符+甚至嵌套的string.Format)。 例如,这将生成所需的字符串,用xlsx.totalCount替换“9”: 试着这样做: string formatString =

我想做一些像

String.Format("Completed {0:9} of ",0) + xlsx.totalCount.ToString();

除了不硬编码9之外,我希望对齐方式是xlsx.totalCount。有什么想法吗?

字符串不必是编译时常量,您可以在运行时构建字符串(使用StringBuilder、运算符+甚至嵌套的string.Format)。 例如,这将生成所需的字符串,用xlsx.totalCount替换“9”:

试着这样做:

string formatString = "{0:" + xlsx.totalCount.ToString() + "}";
String.Format("Completed " + formatString + " of ", 0) + xlsx.totalCount.ToString();

我假设他想要一个9的计数,这取决于xlsx.totalCount的值

StringBuilder sb = new StringBuilder(); sb.Append( '9', xlsx.totalCount ); String.Format( "Completed {0:" + sb.ToString() + "} of ",0) + xlsx.totalCount.ToString(); StringBuilder sb=新的StringBuilder(); sb.追加('9',xlsx.totalCount); Format(“Completed{0:”+sb.ToString()+“}of”,0)+xlsx.totalCount.ToString();
再一次,我觉得应该有一种更简单的方法来构建9链,但显然不是在3分钟内思考。

我在想
string.PadLeft
新字符串(c,count)
。。。 StringBuilder sb = new StringBuilder(); sb.Append( '9', xlsx.totalCount ); String.Format( "Completed {0:" + sb.ToString() + "} of ",0) + xlsx.totalCount.ToString();