C# string formatting with variable space alignment

落花浮王杯 提交于 2019-12-01 20:46:16

问题


I want to do something like

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

except instead of hardcoding a 9 I want the alignment to be whatever xlsx.totalCount is. Any thoughts?


回答1:


Try it like this:

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



回答2:


The string doesn't have to be a compile time constant, you can build the string during runtime (using a StringBuilder, operator+ or even a nested String.Format). This, for instance will produce the needed string with xlsx.totalCount replacing the "9":

String.Format("Completed {0:" + xlsx.totalCount + "} of "...



回答3:


I'd assumed that he wanted a count of 9s depending on the value of xlsx.totalCount.

   StringBuilder sb = new StringBuilder();
   sb.Append( '9', xlsx.totalCount );
   String.Format( "Completed {0:" + sb.ToString() + "} of ",0) + xlsx.totalCount.ToString();

Again, there feels like there should be an easier way of building a chain of 9s, but not in 3 minutes of thinking, apparently.



来源:https://stackoverflow.com/questions/6391319/c-sharp-string-formatting-with-variable-space-alignment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!