O'Reilly logo

Microsoft® Visual Basic® .NET Programmer's Cookbook by Matthew MacDonald

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Pad a String for Fixed-Width Display

Problem

You need to align multiple columns of fixed-width text, perhaps in a Console window or for a printout.

Solution

Pad the text with spaces using PadLeft or PadRight, according to the largest string in the column.

Discussion

The String.PadLeft method adds spaces to the left of a string, whereas String.PadRight adds spaces to the right. Thus, PadLeft right-aligns a string, and PadRight left-aligns it. Both methods accept an integer representing the total length and add a number of spaces equal to the total padded length minus the length of the string.

Dim MyString As String = "Test" Dim NewString As String ' Add two spaces to the left of the string. NewString = MyString.PadLeft(6) ' You can also pad with other ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required