Reader Level:

Padding Strings in C#

By Mahesh Chand on Aug 21, 2010
This code snippet shows how to pad strings in C#.
  • 0
  • 0
  • 16648

Padding Strings

ThePadLeft and PadRight methods can be used to pad strings. The PadLeft method right-aligns and pads a string so that its rightmost character isthe specified distance from the beginning of the string. The PadRight method left-aligns and pads a string so that its rightmost character is aspecified distance from the end of the string. These methods return newString objects that can either be padded with empty spaces or with custom characters. Listign 3 shows how to use these methods.

Listing 3: Using padding methods

string str1 = "My String";
Console.WriteLine(str1.PadLeft(20, '-'));
str2 = "My String";
Console.WriteLine(str2.PadRight(20, '-'));

The output of Listing 3 is shown in Figure 2.


Figure 2.

Read C# Strings  to learn more about strings in C#.

Mahesh Chand

C# Corner founder, 10-times Microsoft MVP, technical author, and software architect. Mahesh authored his first book, A Programmer’s Guide to ADO.NET in C# with APress at the age of 25. C# Corner is a memb... Read more