In VB. NET, when you need to display data on the console or prepare to print data, you may need to adjust the column width to display data of a fixed length. This article describes how to use the padleft method of the string object and the padright method to expand the string for fixed width display.
PadleftAnd padrightMethod
Padleft and padright are two methods of the string class. They can be used to fill spaces on the left and right sides of the string respectively. The two methods accept an integer that represents the total length, and the number of spaces added is equal to the total length of the fill minus the current length of the string.
Note: When formatting a string to a fixed width display, you should use a fixed width font, such as courier, because the fixed width characters share the same width. Otherwise, the filling will be invalid.
Another alternative that programmers often use is to use TAB characters to obtain an approximate fixed-width display format. One problem with using tabs is that when a certain length is longer than the display length, it will expand the tab, which will cause the lines to be not well aligned.
In list A, we show you how to use the padleft and padright methods to display strings. (To run this example, we added a drop-down list listbox1 and set its font to a fixed-width font.) Figure 1 shows the result of running the code in list.
In this example, we define an integer variable I and two string Arrays: strarrseasons and strarrweather. Assign an initial value to each array as a predefined value. Then, we pass each array to the padarray function and specify the expansion on the left side of the string.
Code:
- Private sub padstrings ()
- Dim I as integer = 0
- Dim strarrseasons () asstring = {"Winter", "Spring", "Summer", "fall "}
- Dim strarrweather () asstring = {"cold", "warm", "hot", "cool "}
- Padarray (strarrseasons, true)
- Padarray (strarrweather, false)
- Dim strall as string
- For I = 0 to strarrseasons. Length-1
- Listbox1.items. Add (strarrseasons (I) & "& strarrweather (I ))
- Next
- End sub
- Private sub padarray (byref strarray () as string, byval bpadleft as Boolean)
- Dim I as integer = 0
- Dim imaxlength as integer = 0
- Dim stritem as string
- For each stritem in strarray
- If stritem. length> imaxlength then imaxlength = stritem. Length
- Next
- For I = 0 to strarray. Length-1
- If bpadleft = truettings
- Strarray (I) = strarray (I). padleft (imaxlength)
- Else
- Strarray (I) = strarray (I). padright (imaxlength)
- End if
- Next
- End sub