Alignment and string.Format

T

tstephan

In the docs for String.Format there is an alignment component which
allows you to pad the field to a certain number of spaces.

e.g.
FormatFName = String.Format("First Name = |{0,10}|", myFName);

Pads myFName, width of 10 minimum

I am used to printf which allows a '*' to be used to specify a
variable to be used at runtime to specify the width of the column.

e.g.
printf("%*s", iColWidth, myFName);
Pads myFName, width of iColWidth minimum

Am I missing something or did we lose that power in C#? I would hate
to have to build my format string at runtime just to do this.
 
T

Tom Porterfield

In the docs for String.Format there is an alignment component which
allows you to pad the field to a certain number of spaces.

e.g.
FormatFName = String.Format("First Name = |{0,10}|", myFName);

Pads myFName, width of 10 minimum

I am used to printf which allows a '*' to be used to specify a
variable to be used at runtime to specify the width of the column.

e.g.
printf("%*s", iColWidth, myFName);
Pads myFName, width of iColWidth minimum

Am I missing something or did we lose that power in C#? I would hate
to have to build my format string at runtime just to do this.

As far as I know, that's the only way. Ex:

string myFName = "tom";
int iColWidth = 10;
string FormatFName = string.Format(string.Format("First Name =
|{{0,{0}}}|", iColWidth), myFName);
 
T

tstephan

As far as I know, that's the only way. Ex:

string myFName = "tom";
int iColWidth = 10;
string FormatFName = string.Format(string.Format("First Name =
|{{0,{0}}}|", iColWidth), myFName);

Thanks, that is exactly what I ended up doing - ugly code though. I
am surprised .NET lost functionality however - it would have been easy
to add this.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top