178
LESSON 14 Working With StringS
The first field is {1}. This displays parameter number 1 (the second parameter — remember they’re
zero-based).
The second field is
{0}. This displays the first parameter.
The third field is
{2:C}. This displays the third parameter with the format string C, which formats
the value as currency.
The result is:
You just bought 2 Fiendishly Difficult Puzzles at $9.99 each.
The following code shows an example that uses field widths to make values line up in columns.
Before the code executes, assume that
itemName1, quantity1, and the other variables have already
been initialized.
Console.WriteLine(
string.Format(“{0,-20}{1,5}{2,10}{3,10}“,
“Item”, “Qty”, “Each”, “Total”)
);
Console.WriteLine(
string.Format(“{0,-20}{1,5}{2,10:C}{3,10:C}“,
itemName1, quantity1, priceEach1, quantity1 * priceEach1)
);
Console.WriteLine(
string.Format(“{0,-20}{1,5}{2,10:C}{3,10:C}“,
itemName2, quantity2, priceEach2, quantity2 * priceEach2)
);
Console.WriteLine(
string.Format(“{0,-20}{1,5}{2,10:C}{3,10:C}“,
itemName3, quantity3, priceEach3, quantity3 * priceEach3)
);
Notice that the code begins with a line that defines the column headers. Its formatting string uses
the same indexes and alignment values as the other formatting strings so the headers line up with the
values below.
The following shows the result:
Item Qty Each Total
Pretzels (dozen) 4 $5.95 $23.80
Blue laser pointer 1 $149.99 $149.99
Titanium spork 2 $8.99 $17.98
Because the format string is just a string, you could define it in a constant or
variable and then use that variable as the first argument to the
Format method.
That way you are certain that all of the
Format statements use the same string.
This also makes it easier to change the format later if necessary.
Every object provides a ToString method that converts the object into a string. For simple data types
such as numbers and dates, the result is the value in an easy-to-read string.
596906c14.indd 178 4/7/10 12:32:53 PM