Format Strings in Console.WriteLine method

前端 未结 3 495
悲&欢浪女
悲&欢浪女 2020-12-02 17:11

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

Console.WriteLine( \"{0}{1,10}\", \"Face\", \"Frequency\" ); //Headings
Console.Writ         


        
相关标签:
3条回答
  • 2020-12-02 18:02

    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

    0 讨论(0)
  • 2020-12-02 18:10

    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]}
    
    0 讨论(0)
  • 2020-12-02 18:13

    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∙∙∙∙∙∙∙]
    
    0 讨论(0)
提交回复
热议问题