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 the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.