Format Strings in Console.WriteLine method
Solution 1
It adds padding to the left. Very useful for remembering the various string formatting patterns is the following 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∙∙∙∙∙∙∙]
Solution 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]}
Solution 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
Related videos on Youtube
Joe
Updated on July 09, 2022Comments
-
Joe almost 2 years
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}
? -
Joe over 13 yearsThanks for the reply 0xA3. If i understand correctly,does that mean {1,10} would print the second argument and 10 spaces immediately following it ?
-
Dirk Vollmar over 13 years@Joe: No, padding means that the string is filled up with blanks up to the length specified, see the example in my answer.
-
Graham Clark over 13 yearsAs far as I can see, this cheat sheet is completely wrong! The wrong index is used, and the positive/negative alignment is the opposite of what really happens. So, to produce
[∙∙∙∙∙∙∙Foo]
, you'd actually doString.Format("[{0, 10}]", "Foo");