Re: String.Format with a variable field width
- From: MC <nospam@xxxxxxxxxxx>
- Date: Sun, 30 Apr 2006 19:22:04 GMT
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
On Sun, 30 Apr 2006 23:12:00 +1000, JasonS <gadget@xxxxxxxxxx> wrote:
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
On Sun, 30 Apr 2006 05:31:15 GMT, MC wrote:
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
On Sat, 29 Apr 2006 15:31:23 +0100, "Buddy Home" <BuddyHome@xxxxxxxx>
wrote:
Use
string.format("{0}{1}", myField1, myField2);
Buddy Home
MCSD.Net
"MC" <nospam@xxxxxxxxxxx> wrote in message
news:6ml552he74q9ov6rn4jftc98stfu03nfr7@xxxxxxxxxx
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
.
- References:
- String.Format with a variable field width
- From: MC
- Re: String.Format with a variable field width
- From: Buddy Home
- Re: String.Format with a variable field width
- From: MC
- Re: String.Format with a variable field width
- From: JasonS
- String.Format with a variable field width
- Prev by Date: Re: .NET 2.0 performance bug in ArrayList.Sort (its getting hotter!)
- Next by Date: Re: .NET 2.0 performance bug in ArrayList.Sort
- Previous by thread: Re: String.Format with a variable field width
- Next by thread: Give facility to user to change report.
- Index(es):
Relevant Pages
|