Partilhar via


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.

Dim MyString As String = "Hello World!"
Console.WriteLine(MyString.PadLeft(20, "-"c))
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.

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