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 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.

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

PadRight

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.

Dim MyString As String = "Hello World!"
Console.WriteLine(MyString.PadRight(20, "-"c))
string MyString = "Hello World!";
Console.WriteLine(MyString.PadRight(20, '-'));

See Also

Other Resources

Basic String Operations