String.Format with a variable field width

M

MC

In C, printf allows us to specify a runtime (non-constant) field width
of a formatted value by using the * character. Is there something
like that for System.String.Format? In C#, I find myself having to
use concatenation, which is awkward to write and to read:

s.Format("{0," + fieldWidth.ToString() + "}", val);

Preferably, I'd like to nest two placeholders, like this:

s.Format("{0,{1}}", val, fieldWidth);

but it doesn't like that (Framework 2.0).

Is currently available somehow? I didn't see it in MSDN. If not, was
there never any noise about the lack of it in Framework 1.x?? And are
there any plans to add it in the near future?

Thanks,
Craig
 
M

MC

Buddy,

Thanks for replying but I really don't think that will do what I want.
In my example, I want to output just one value, formatted with an
"alignment" value that is specified by a variable instead of by a
constant. I believe your snippet will output two values with no
alignment specified, no?

Craig
 
J

JasonS

You have to build the string to pass to the Format function, resulting in a
rather messy:

Console.WriteLine(string.Format(string.Format("{{0,{0}}}",wid),val));

Double braces are ignored by the format function, so if wid is 9 then this
gives {0,9}.

I would simply use concatenation, as it has much lower overhead and is far
easier to read :)

Cheers,
Jason
 
M

MC

Jason,

Yes, I agree, that's nasty. I suppose I could use
..ToString(formatString) and .PadLeft or .PadRight to get the same
result as with placeholders, and I could even use StringBuilder to be
even more efficient.

Something like:

StringBuilder sb = new StringBuilder();
sb.Append("Item".PadRight(width));
sb.Append("Cost\n");
sb.Append("=========================\n");
foreach(Item item in items)
{
sb.Append(item.Description.PadRight(width));
sb.Append(item.Cost.ToString("C"));
sb.Append("\n");
}

It's still verbose compared with the * in printf but it's readable.

Thanks,
Craig
 

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