2

{0,N} formatting pads a string to the left with spaces. For example:

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]);

Which results in lines with a total length of 16 characters:

A                A
Bob            Bob
Charles    Charles

You can achieve the same thing with String.PadLeft, for example:

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

This attempt to add a parameter to {0,N} formatting compiles, but throws an exception at runtime:

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

Is it possible to pass a parameter into {0,N} style formatting?

0

1 Answer 1

4

You can use string interpolation and double the braces for the format pattern:

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

int paddingMax = 16;

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

Output:

A              A
Bob          Bob
Charles  Charles

To check for outbreaks:

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.