
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
64
|
Chapter 2: Strings and Characters
Solution
The static string.Format method allows you to format strings in a variety of ways.
For example:
int ID = 12345;
double weight = 12.3558;
char row = 'Z';
string section = "1A2C";
string output = string.Format(@"The item ID = {0:G} having weight = {1:G}
is found in row {2:G} and section {3:G}", ID, weight, row,
section);
Console.WriteLine(output);
output = string.Format(@"The item ID = {0:N} having weight = {1:E}
is found in row {2:E} and section {3:E}", ID, weight, row,
section);
Console.WriteLine(output);
output = string.Format(@"The item ID = {0:N} having weight = {1:N}
is found in row {2:E} and section {3:D}", ID, weight, row,
section);
Console.WriteLine(output);
output = string.Format(@"The item ID = {0:(#####)} having weight = {1:0000.00}
lbs is found in row {2} and section {3}", ID, weight, row,
section);
Console.WriteLine(output);
The output is as follows:
The item ID = 12345 having weight = 12.3558 is found in row Z and section 1A2C
The item ID = 12,345.00 having weight = 1.235580E+001 is found
in row Z and section 1A2C
The item ID = 12,345.00 having weight = 12.36 is found in row Z and section 1A2C
The item ID = (12345) having weight = 0012.36 lbs is found in row Z and section 1A2C
To simplify things, the string.Format method can be