PadLeft example. This program creates an array filled with 3 Strings. It then loops over these Strings. Each String has up to five characters of padding added to the left.
And This new String returned by PadLeft is then passed to Console.WriteLine.
Info PadLeft does not modify the String data. Instead it creates a modified String in new memory.
So This means the String Dim you call it on—in this program "w"—is not modified in any way.
Module Module1
Sub Main()
Dim words() As String = {"A", "Net", "Perls"}
' Loop over words.
For Each w As String In words
Console.WriteLine(w.PadLeft(5))
Next
End Sub
End Module A
Net
Perls
PadRight example. The PadLeft Function is paired with PadRight. Here we add complexity by using a Dictionary collection. For keys we use Strings. For values we use Integers.
Module Module1
Sub Main()
' Create Dictionary.
Dim dict As Dictionary(Of String, Integer) = New Dictionary(Of String, Integer)
dict.Add("Cat", 5)
dict.Add("Mouse", 1)
dict.Add("Leopard", 9)
dict.Add("Asp", 10)
' Loop over pairs.
For Each pair As KeyValuePair(Of String, Integer) In dict
' Pad right of key.
Console.Write(pair.Key.PadRight(10))
' Pad left of value.
Console.WriteLine(pair.Value.ToString().PadLeft(2))
Next
End Sub
End ModuleCat 5
Mouse 1
Leopard 9
Asp 10
Example 3. PadLeft and PadRight can add any Char value you like. In this program we use a period as the second argument to PadRight. And for PadLeft we pass a hash sign.
And The output String contains padding with these special characters, not spaces.
Module Module1
Sub Main()
' Pad with . and #
Console.Write("Sam".PadRight(10, "."c))
Console.WriteLine("28173".PadLeft(6, "#"c))
' Next line.
Console.Write("Mark".PadRight(10, "."c))
Console.WriteLine("137".PadLeft(6, "#"c))
End Sub
End ModuleSam.......#28173
Mark......137
Summary. Text-based display of data is common. It is an easy way to format tables in console programs. PadLeft and PadRight help in code that displays numeric data.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.