Format Strings in Console.WriteLine method

2020-01-29 04:18发布

问题:

Im new to C# programming. Can someone please explain the following code:

Console.WriteLine( "{0}{1,10}", "Face", "Frequency" ); //Headings
Console.WriteLine( "{0,4}{1,10}",someval,anotherval);

I understand that this prints two columns of values with the headings given, and {0} refers to the first argument given. But what is the meaning of the format strings of the form {x,y} ?

回答1:

It adds padding to the left. Very useful for remembering the various string formatting patterns is the following cheat sheet:

.NET String.Format Cheat Sheet

Positive values add padding to the left, negative add padding to the right

Sample                                 Generates
String.Format("[{0, 10}]", "Foo");     [∙∙∙∙∙∙∙Foo]
String.Format("[{0, 5}]", "Foo");      [∙∙Foo]
String.Format("[{0, -5}]", "Foo");     [Foo∙∙]
String.Format("[{0, -10}]", "Foo");    [Foo∙∙∙∙∙∙∙]


回答2:

When you see {x,y}, x represents the argument's index and y the alignment, as specified here. The complete syntax is the following:

{index[,alignment][:formatString]}


回答3:

This is a padding value...if the argument isn't the length that is specified, it puts spaces in.

E.g. if you had {0,10} and the argument for {0} was "Blah", the actual value printed would be "Blah<SPACE><SPACE><SPACE><SPACE><SPACE><SPACE>"...Blah, with 6 extra spaces to make up a string of 10 length

ps - not sure how to put actual spaces in...need to look up SO faq no doubt