我有一个字符串(如下所示),我希望每个参数都居中对齐。
有一个左对齐选项(“+”)和右对齐选项(“-”),但我想居中对齐。
basketItemPrice = string.Format("\n\n{0, -5}{1, -14:0.00}{2, -18:0.00}{3,-14:0.00}{4,6}{5,-12:0.00}", item.Quantity, item.OrderItemPrice, item.MiscellaniousCharges, item.DiscountAmountTotal, "=", item.UpdateItemAmount(Program.currOrder.OrderType));
最佳答案
不幸的是,String.Format
本身不支持它。您必须自己填充字符串:
static string centeredString(string s, int width)
{
if (s.Length >= width)
{
return s;
}
int leftPadding = (width - s.Length) / 2;
int rightPadding = width - s.Length - leftPadding;
return new string(' ', leftPadding) + s + new string(' ', rightPadding);
}
使用示例:
Console.WriteLine(string.Format("|{0}|", centeredString("Hello", 10)));
Console.WriteLine(string.Format("|{0}|", centeredString("World!", 10)));
关于c# - 如何在格式字符串中居中对齐参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18573004/