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 ...

Get Microsoft® Visual Basic® .NET Programmer's Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.