添加用于填充字符串的参数 (C#)

Add parameters for padding a string (C#)

{0,N} 格式在字符串左侧填充空格。例如:

string [] names = { "A", "Bob", "Charles" };
Console.WriteLine("{0}{0,15}", names[0]);
Console.WriteLine("{0}{0,13}", names[1]);
Console.WriteLine("{0}{0,10}", names[2]);

这导致总长度为 16 个字符的行:

A                A
Bob            Bob
Charles    Charles

你可以用String.PadLeft达到同样的效果,例如:

foreach (var name in names)
{
    Console.WriteLine("{0}{1}", name, name.PadLeft(16-name.Length, ' '));
}

此尝试将参数添加到 {0,N} 格式化编译,但在运行时抛出异常:

foreach (var name in names)
{
    Console.WriteLine("{0}{0,16-name.Length}", name);
}

是否可以将参数传递到 {0,N} 样式格式中?

您可以使用 string interpolation 和双括号格式模式:

string[] names = { "A", "Bob", "Charles" };

int paddingMax = 16;

foreach (string name in names)
  Console.WriteLine($"{{0}}{{0,{paddingMax - name.Length}}}", name);

输出:

A              A
Bob          Bob
Charles  Charles

检查爆发:

foreach ( string name in names )
{
  int padding = paddingMax - name.Length;
  if ( padding < 0 )
    Console.WriteLine("Padding error for: " + name);
  else
    Console.WriteLine($"{{0}}{{0,{padding}}}", name);