Detailed explanation of C# formatted output

Table of contents

1. Use Write

2. Use WriteLine

3. Format string

1. Use Alternative Markup

2. Use string difference (C#6.0):

 4. Multiple tags and values

 5. Formatting numeric strings


1. Use Write

Console.Write("Hello, World!");

Output result:

2. Use WriteLine

Console.WriteLine("Hello, World!");
Console.WriteLine("Hello, World!");
Console.WriteLine("Hello, World!");

Output result:

3. Format string

1. Use Alternative Markup

The following statement has two substitution tokens: 0 and 1; and two substitution values: 3 and 6:

Console.WriteLine("they are {0} and {1}.", 3, 6);

2. Use string interpolation (C#6.0):

Note: Need to add mark "$" in front.

int num1 = 10;
string s1 = "hello";
Console.WriteLine($"They are {num1} and {s1}.");

Output result:

 4. Multiple tags and values

In C#, any number of substitution flags and any number of values ​​can be used:

Console.WriteLine("There are {1}, {0} and {1}.", 3, 6);

 Output result:

 Note that the token cannot exceed a value at a position other than the length of the replaced value list, otherwise a runtime error will be generated:

Console.WriteLine("There are {2}, {0} and {1}.", 3, 6);

Output result:

 5. Formatting numeric strings

 for example:

int temp = 100;
Console.WriteLine("{0}",500);        //50
Console.WriteLine("{0,10}", 500);    //       500
Console.WriteLine("{0,10:C}", 500);  //   ¥500.00  (右对齐)
Console.WriteLine("{0,-10:C}", 500); //¥500.00     (左对齐)
Console.WriteLine("{0,10:C5}", 500); //¥500.00000
Console.WriteLine($"{temp,10:C5}");  //¥100.00000

The meaning of the third sentence Console: output item 0 (500) in the list , and format it as currency (¥500.00), and make the output result right-aligned in 10 fields (there are 3 spaces in front of ¥500.00).

The meaning of the fifth sentence Console: output the 0th item (500) in the list , and format it as currency (¥500.00), keep 5 decimal places (¥500.00000), and make the output result right-aligned in 10 fields ( There is no space before ¥500.00000, because 10 fields have been filled).

There are many formatting characters besides "C". The following table lists some commonly used formatting characters:

Guess you like

Origin blog.csdn.net/m0_56494923/article/details/124504902