【问题标题】:Using String.Format To Dynamically Provide The Max Amount of Padding Needed使用 String.Format 动态提供所需的最大填充量
【发布时间】:2015-01-09 00:29:33
【问题描述】:

您好,我正在尝试使我的控制台应用程序分配更美观,通过这样做,我决定在我的循环中实现 String.Format。我们没有学过它,但它很容易上手。这里的主要问题是如何将 int 解析为 String.Format 以便它提供所需的最大空间。

这是循环:

for (int index = 0; index < files.Length; index++)
{
    int maxNumericalSize = 2;
    int fileNumberSystem = index + 1;
    string result = string.Format("{0,maxNumericalSize}: {1,20} - {2,10} - {3}", fileNumberSystem, files[index].Name, files[index].Length, files[index].LastWriteTime );
    /* Console.WriteLine(fileNumberSystem + ". " + files[index].Name + " - " + files[index].Length + " - " + files[index].LastWriteTime); */
    Console.WriteLine(result);
}

如您所见,MaxNumericalSize 显然会抛出一个区域,因为它在语音标记内,所以我目前想知道如何将它解析为 String.Format 而不会出现错误。

【问题讨论】:

  • 如果这是一个问题,您可以将int 转换为string 并填充它。如果您显示当前的输出并期望一个理解您想要的东西会更好(对不起,但我没有)。
  • 字符串结果 = string.Format("{0,"+maxNumericalSize+"}: {1,20} - {2,10} - {3}", fileNumberSystem, files[index].Name , 文件[索引].长度, 文件[索引].LastWriteTime );应该工作

标签: c# string.format


【解决方案1】:

尝试使用string.PadLeft/string.PadRight添加额外的空格,如下所示

string.Format("{0}: {1,20} ..", fileNumberSystem.ToString().PadRight(maxNumericalSize), ...);

对于PadRight,它的工作原理是这样的

返回一个新字符串,该字符串左对齐该字符串中的字符 在右侧用空格填充它们,达到指定的总长度。

甚至还有一个重载,让您可以选择一个角色来填充空间。您可以在MSDN 上找到更多信息。

【讨论】:

    猜你喜欢
    • 2015-04-29
    • 2020-04-20
    • 2011-09-15
    • 2017-06-11
    • 1970-01-01
    • 1970-01-01
    • 2017-04-18
    • 1970-01-01
    • 2018-12-18
    相关资源
    最近更新 更多