Padding Strings in .NET

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 a space or a specified character. The resulting string appears to be either right-aligned or left-aligned. If the original string's length is already equal to or greater than the desired total length, the padding methods return the original string unchanged; for more information, see the Returns sections of the two overloads of the String.PadLeft and String.PadRight methods.

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.

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

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.

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

See also