【问题标题】:C# string formatting with variable space alignment具有可变空间对齐的 C# 字符串格式化
【发布时间】:2019-08-14 02:28:17
【问题描述】:

我想做类似的事情

String.Format("Completed {0:9} of ",0) + xlsx.totalCount.ToString();

除了硬编码 9 之外,我希望对齐是 xlsx.totalCount 的任何值。有什么想法吗?

【问题讨论】:

  • 我在想string.PadLeftnew string(c, count)...

标签: c# string-formatting


【解决方案1】:

试试这样:

string formatString = "{0:" + xlsx.totalCount.ToString() + "}";
String.Format("Completed " + formatString + " of ", 0) + xlsx.totalCount.ToString();

【讨论】:

    【解决方案2】:

    字符串不必是编译时常量,您可以在运行时构建字符串(使用 StringBuilder、operator+ 甚至嵌套的 String.Format)。 例如,这将生成所需的字符串,其中 xlsx.totalCount 替换“9”:

    String.Format("Completed {0:" + xlsx.totalCount + "} of "...
    

    【讨论】:

      【解决方案3】:

      我假设他希望根据 xlsx.totalCount 的值计数 9。

      StringBuilder sb = new StringBuilder(); sb.Append('9', xlsx.totalCount); String.Format("已完成 {0:" + sb.ToString() + "} of ",0) + xlsx.totalCount.ToString();

      再一次,感觉应该有一种更简单的方法来构建一个 9 链,但显然不是在 3 分钟的思考中。

      【讨论】:

        猜你喜欢
        • 2013-10-10
        • 2022-11-30
        • 2012-01-04
        • 1970-01-01
        • 2013-11-01
        • 2017-04-20
        相关资源
        最近更新 更多