Padding Strings
You can use one of the following methods to create a new version of an existing string that is right-aligned or left-aligned a specified number of spaces. The new string can either be padded with empty spaces (also called white spaces) or with custom characters.
Method name | Use |
---|---|
String.PadLeft | Right-aligns and pads a string so that its rightmost character is a specified distance from the beginning of the string. |
String.PadRight | Left-aligns and pads a string so that its rightmost character is a specified distance from the end of the string. |
PadLeft
The String.PadLeft method creates a new string that is right-aligned so that its last character is a specified number of spaces from the first index of the string. White spaces are inserted if you do not use an override that allows you to specify your own custom padding character.
The following example uses the PadLeft method to create a new string that has a total length of twenty spaces.
Dim MyString As String = "Hello World!"
Console.WriteLine(MyString.PadLeft(20, "-"c))
[C#]
string MyString = "Hello World!";
Console.WriteLine(MyString.PadLeft(20, '-'));
This example displays --------Hello World!
to the console.
PadRight
The String.PadRight method creates a new string that is left-aligned so that the current string is extended a specified number of spaces to the right of the string's first index. This method fills in the new string with white spaces if you do not specify a custom character.
The following example uses the PadRight method to create a new string that has a total length of twenty spaces.
Dim MyString As String = "Hello World!"
Console.WriteLine(MyString.PadRight(20, "-"c))
[C#]
string MyString = "Hello World!";
Console.WriteLine(MyString.PadRight(20, '-'));
This example displays Hello World!--------
to the console.