Padding Strings in the .NET Framework

Use one of the following String methods to create a new string that consists of an original string that is padded with leading or trailing characters to a specified total length. The padding character can be spaces or a specified character, and consequently appears to be either right-aligned or left-aligned.

Method name

Use

String.PadLeft

Pads a string with leading characters to a specified total length.

String.PadRight

Pads a string with trailing characters to a specified total length.

The String.PadLeft method creates a new string by concatenating enough leading pad characters to an original string to achieve a specified total length. The String.PadLeft(Int32) method uses white space as the padding character and the String.PadLeft(Int32, Char) method enables you to specify your own padding character.

The following code example uses the PadLeft method to create a new string that is twenty characters long. The example displays "--------Hello World!" to the console.

string MyString = "Hello World!";
Console.WriteLine(MyString.PadLeft(20, '-'));

The String.PadRight method creates a new string by concatenating enough trailing pad characters to an original string to achieve a specified total length. The String.PadRight(Int32) method uses white space as the padding character and the String.PadRight(Int32, Char) method enables you to specify your own padding character.

The following code example uses the PadRight method to create a new string that is twenty characters long. The example displays "Hello World!--------" to the console.

string MyString = "Hello World!";
Console.WriteLine(MyString.PadRight(20, '-'));
Was this page helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2015 Microsoft