简体   繁体   中英

Formatting C# String

I would like to print out information about products to the console line, and the code I have that does it is this:

const string format = "[PRODUCT_ID] {0, -10} | [SIZE] {1, -10} | [PRICE] {2, -10}"
foreach (DataRow row in productTable.Rows)
{
    Console.WriteLine(string.Format(format, row["PRODUCT_ID"], row["SIZE"], row["PRICE"]));
}

Ideally, I would like all the " | " to be lined up for the expected output to be:

[PRODUCT_ID] 25439  | [SIZE] XS | [PRICE] 34.55 USD

[PRODUCT_ID] 25438  | [SIZE] XL | [PRICE] 27.99 USD

[PRODUCT_ID] 142367 | [SIZE] S  | [PRICE] 27.99 USD

[PRODUCT_ID] 352344 | [SIZE] M  | [PRICE] 12.50 USD

But, in reality, the actual output in the console looks like:

[PRODUCT_ID] 25439 | [SIZE] XS | [PRICE] 34.55 USD

[PRODUCT_ID] 25438 | [SIZE] XL | [PRICE] 27.99 USD

[PRODUCT_ID] 142367 | [SIZE] S | [PRICE] 27.99 USD

[PRODUCT_ID] 352344 | [SIZE] M | [PRICE] 12.50 USD
const string format = "[PRODUCT_ID] {0} | [SIZE] {1} | [PRICE] {2}";
foreach (DataRow row in productTable.Rows)
{
    Console.WriteLine(string.Format(format, 
        row["PRODUCT_ID"].PadRight(10, ' '),
        row["SIZE"].PadRight(10, ' '),
        row["PRICE"].PadRight(10, ' ')));
}

https://learn.microsoft.com/en-US/do.net/standard/base-types/padding

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM