Книга: C# 2008 Programmer

String Formatting

String Formatting

You've seen the use of the Console.WriteLine() method to print the output to the console. For example, the following statement prints the value of num1 to the console:

int num1 = 5;
Console.WriteLine(num1); //---5---

You can also print the values of multiple variables like this:

int num1 = 5;
int num2 = 12345;
Console.WriteLine(num1 + " and " + num2); //---5 and 12345---

If you have too many variables to print (say more than five), though, the code can get messy very quickly. A better way would be to use a format specifier, like this:

Console.WriteLine("{0} and {1}", num1, num2); //---5 and 12345---

A format specifier ({0}, {1}, and so forth) automatically converts all data types to string. Format specifiers are labeled sequentially ({0}, {1}, {2}, and so on). Each format specifier is then replaced with the value of the variable to be printed. The compiler looks at the number in the format specifier, takes the argument with the same index in the argument list, and makes the substitution. In the preceding example, num1 and num2 are the arguments for the format specifiers.

What happens if you want to print out the value of a number enclosed with the {} characters? For example, say that you want to print the string {5} when the value of num1 is 5. You can do something like this:

num1 = 5;
Console.WriteLine("{{{0}}}", num1); //---{5}---

Why are there two additional sets of {} characters for the format specifier? Well, if you only have one additional set of {} characters, the compiler interprets this to mean that you want to print the string literal {0}, as the following shows:

num1 = 5;
Console.WriteLine("{{0}}", num1); //---{0}---

The two additional sets of {} characters indicate to the compiler that you want to specify a format specifier and at the same time surround the value with a pair of {} characters.

And as demonstrated earlier, the String class contains the Format() static method, which enables you to create a new string (as well as perform formatting on string data). The preceding statement could be rewritten using the following statements:

string formattedString = string.Format("{{{0}}}", num1);
Console.WriteLine(formattedString); //---{5}---

To format numbers, you can use the format specifiers as shown here:

num1=5;
Console.WriteLine("{0:N}", num1); //---5.00---
Console.WriteLine("{0:00000}", num1);- //---00005---
//---OR---
Console.WriteLine("{0:d5}", num1); //---00005---
Console.WriteLine("{0:d4}", num1); //---0005---
Console.WriteLine("{0,5:G}", num1);--- //---    5 (4 spaces on left)---

For a detailed list of format specifiers you can use for formatting strings, please refer to the MSDN documentation under the topics "Standard Numeric Format Strings" and "Custom Numeric Format Strings. "

You can also print out specific strings based on the value of a number. Consider the following example:

num1 = 0;
Console.WriteLine("{0:yes;;no}", num1); //---no--
num1 = 1;
Console.WriteLine("{0:yes;;no}", num1); //---yes---
num1 = 5;
Console.WriteLine("{0:yes;;no}", num1); //---yes---

In this case, the format specifier contains two strings: yes and no. If the value of the variable (num) is nonzero, the first string will be returned (yes). If the value is 0, then it returns the second string (no). Here is another example:

num1 = 0;
Console.WriteLine("{0:OK;;Cancel}", num1); //---Cancel---
num1 = 1;
Console.WriteLine("{0:OK;;Cancel}", num1); //---OK---
num1 = 5;
Console.WriteLine("{0:OK;;Cancel}", num1); //---OK---

For decimal number formatting, use the following format specifiers:

double val1 = 3.5;
Console.WriteLine("{0:##.00}", val1);-- //---3.50---
Console.WriteLine("{0:##.000}", val1);- //---3.500---
Console.WriteLine("{0:0##.000}", val1); //---003.500---

There are times when numbers are represented in strings. For example, the value 9876 may be represented in a string with a comma denoting the thousandth position. In this case, you cannot simply use the Parse() method from the int class, like this:

string str2 = "9,876";
int num3 = int.Parse(str2); //---error---

To correctly parse the string, use the following statement:

int num3 = int.Parse(str2,
 System.Globalization.NumberStyles.AllowThousands);
Console.WriteLine(num3); //---9876---

Here is another example:

string str3 = "1,239,876";
num3 = int.Parse(str3,
 System.Globalization.NumberStyles.AllowThousands);
Console.WriteLine(num3); //---1239876---

What about the reverse — formatting a number with the comma separator? Here is the solution:

num3 = 9876;
Console.WriteLine("{0:#,0}", num3); //---9,876---
num3 = 1239876;
Console.WriteLine("{0:#,0}", num3); //---1,239,876---

Last, to format a special number (such as a phone number), use the following format specifier:

long phoneNumber = 1234567890;
Console.WriteLine("{0:###-###-####}", phoneNumber); //---123-456-7890---

Оглавление книги


Генерация: 1.090. Запросов К БД/Cache: 3 / 0
поделиться
Вверх Вниз