Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# string formatting with variable space alignment

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?

like image 620
Andrew Avatar asked Jun 17 '11 20:06

Andrew


2 Answers

Try it like this:

string formatString = "{0:" + xlsx.totalCount.ToString() + "}";
String.Format("Completed " + formatString + " of ", 0) + xlsx.totalCount.ToString();
like image 81
bradenb Avatar answered Sep 20 '22 14:09

bradenb


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 "...
like image 24
Neowizard Avatar answered Sep 19 '22 14:09

Neowizard