Nifty .NET Part #3: String.PadLeft

And there is part 3, String.PadLeft, this method will add a specified character to the left side of string till the specified length is met.

The method definition:

public string PadLeft(int totalWidth, char paddingChar)

So what can you to with the PadLeft method in practice? The following code sample will add leading zero’s only when it’s needed:

   1:  using System;
   3:  public class MyClass
   4:  {
   5:      public static void Main()
   6:      {
   7:          // Displays: 001
   8:          Console.WriteLine("1".PadLeft(3, '0'));
  10:          // Displays: 010
  11:          Console.WriteLine("10".PadLeft(3, '0'));
  13:          // Displays: 100
  14:          Console.WriteLine("100".PadLeft(3, '0'));
  16:          Console.ReadLine();
  17:      }
  18:  }

As you can see if the string length is already equal to the total width of the PadLeft the zero isn’t added.

There is also an overload of the PadLeft method, this method will add spaces till the total width is met.

public string PadLeft(int totalWidth)

As you probably expected there is also a PadRight method, this will do the opposite of the PadLeft method.

You can find more info and examples on the MSDN pages:

No Comments