Padding Strings In C#

This code snippet shows how to pad strings in C# and .net core. Padding in string is adding a space or other character at the beginning or end of a string. String class has String.PadLeft() and String.PadRight() methods to pad strings in left and right sides.

Padding in string is adding a space or other character at the beginning or end of a string. The String class has String.PadLeft() and String.PadRight() methods to pad strings in left and right sides.

In C#, Strings are immutable. That means the method does not update the existing string but returns a new string.

String.PadLeft()

String.PadLeft() method has two overloaded forms.

MethodDescription
PadLeft(Int32)Returns a new string that right-aligns the characters in this instance by padding them with spaces on the left, for a specified total length.
PadLeft(Int32, Char)Returns a new string that right-aligns the characters in this instance by padding them on the left with a specified Unicode character, for a specified total length.

Example

The following example replaces all commas with colons in a string.

  1. // Pad left example  
  2. string hello = "Hello C# Corner.";  
  3. // Make string size 50. All left side will be spaces  
  4. string hello50 = hello.PadLeft(50);  
  5. Console.WriteLine(hello50);  
  6. // Pad left with a character  
  7. string helloHash = hello.PadLeft(50, '#');  
  8. Console.WriteLine(helloHash); 

Listing 1.

The output of Listing 1 looks like Figure 1.

Padding Strings in C#
Figure 1.

String.PadRight()

String.PadRight() method has two overloaded forms.

MethodDescription
PadRight(Int32)Returns a new string that left-aligns the characters in this string by padding them with spaces on the right, for a specified total length.
PadRight(Int32, Char)Returns a new string that left-aligns the characters in this string by padding them on the right with a specified Unicode character, for a specified total length.

Example

The following example replaces all commas with colon in a string.

  1. // Pad right example  
  2. string hello = "Hello C# Corner.";  
  3. // Make string size 50. All right side will be spaces  
  4. string hello50 = hello.PadRight(50);  
  5. Console.WriteLine(hello50);  
  6. // Pad right with a character  
  7. string helloHash = hello.PadRight(50, '#');  
  8. Console.WriteLine(helloHash);  

Listing 2.

The output of Listing 2 looks like Figure 2.

Padding Strings in C#
Figure 2