What do the curly braces mean in C# strings?

后端 未结 5 1801
情书的邮戳
情书的邮戳 2021-02-14 22:40
while (rdr.Read())
{
    Console.WriteLine(\"Product: {0,-35} Total: {1,2}\", rdr[\"ProductName\"], rdr[\"Total\"]);
}

What does {0,-35} mean in this c

5条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-14 23:16

    A more simple line would be:

    Console.WriteLine("{0}", 5);
    

    The function accepts any number of arguments. They will be inserted into the string at the corresponding index. In this case, index zero holds the integer 5. The result is the string "5".

    Now, you have the option the specify a format string as well as an index. Like so:

    Console.WriteLine("{0:0.00}", 5);
    

    This formats the 5 with 0.00, resulting in 5.00.

    Thats the case for numbers, but I think those are more easy to explain. For strings, the "format" implies alignment. Also note that you use a comma rather than a colon to separate index and format.

    alignment (optional): This represent the minimal length of the string. Postive values, the string argument will be right justified and if the string is not long enough, the string will be padded with spaces on the left. Negative values, the string argument will be left justied and if the string is not long enough, the string will be padded with spaces on the right. If this value was not specified, we will default to the length of the string argument.

    So in your example:

    • {0,-35} means string has to be at least 35 characters, leftjustified (space padding on the end).
    • {1,2} means string has to be at least 2 characters, rightjustified (space padding in front).

    I recommend this article, as well as the string.Format documentation.

提交回复
热议问题