c# - 如何在格式字符串中居中对齐参数

标签 c#

我有一个字符串(如下所示),我希望每个参数都居中对齐。

有一个左对齐选项(“+”)和右对齐选项(“-”),但我想居中对齐。

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/

相关文章:

c# - 根据旋转角度计算X Y 运动?

c# - 如何确定本地主机的 IPv4 地址?

c# - 通过 PIA 接口(interface)类型获取 CLSID

c# - 如何在 app.config 中存储用户可调整的配置?

c# - visual studio - 扩展方法的奇怪错误

c# - 尝试下载单词时出现“无法访问关闭的流”之类的错误

c# - C# Endian 敏感吗?

c# - 如何将unicode字符串从c#传输到c/c++ dll

c# - 将参数发送到 jquery 回调

c# - 如何在 ASP.NET MVC 3 中的 HTTPContext 响应中添加 header ?