Padding Strings
Important This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here. ArchiveDisclaimer

Padding Strings 

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.

PadLeft

The System.String.PadLeft method creates a new string by concatenating enough leading pad characters to an original string to achieve a specified total length. The System.String.PadLeft(System.Int32) method uses white space as the padding character and the System.String.PadLeft(System.Int32,System.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, '-'));

PadRight

The System.String.PadRight method creates a new string by concatenating enough trailing pad characters to an original string to achieve a specified total length. The System.String.PadRight(System.Int32) method uses white space as the padding character and the System.String.PadRight(System.Int32,System.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, '-'));

See Also

Show:
© 2016 Microsoft