Recipe 5.29. Padding a String for Exact Length and Alignment


Problem

You want to pad a string with spaces (or some other character) either on the head end, the tail end, or both ends, such that the resulting string is n characters in total length.

Solution

Sample code folder: Chapter 05\PadString

Use the String. PadLeft() and String.PadRight() methods to pad the head and tail ends of the string, respectively, and use a calculated combination of these two methods to pad the string on both ends.

Discussion

The PadLeft() and PadRight() methods take a count value that defines the target length of the string after sufficient spaces are concatenated to it. An optional second parameter provides a character to use for the padding if you want something other than spaces to be used. In the first block of code the default space characters are used for the padding:

 Dim content1 As String Dim content2 As String Dim content3 As String Dim content4 As String content1 = "Not padded" content2 = "PadLeft".PadLeft(50) content3 = "PadRight".PadRight(50) content4 = "PadCenter" content4 = content4.PadLeft((50 + _    content4.Length) \ 2).PadRight(50) MsgBox(String.Format("{0}{4}{1}{4}{2}{4}{3}", _    content1, content2, content3, content4, vbNewLine)) 

The PadCenter() calculation adds half of the required padding characters to the head end of the string, then pads out the right end to the target length. The PadLeft() method is applied to the string first, and the PadRight() method is applied to the result, all in a single line. Figure 5-32 shows the strings with the padding causing the text to align to the left, right, and middle, depending on where the padding was applied.

Figure 5-32. Padding strings with spaces at the head, the tail, or both ends


Padding with spaces is often what you want to do in a real-world application, but for display purposes it isn't very helpful. In Figure 5-32, for instance, you can't tell that "PadRight" has 50spaces at its end. Therefore, let's recode this example, padding the strings with periods instead:

 content1 = "Not padded" content2 = "PadLeft".PadLeft(50, "."c) content3 = "PadRight".PadRight(50, "."c) content4 = "PadCenter" content4 = content4.PadLeft((50 + content4.Length) \ 2, _    "."c).PadRight(50, "."c) MsgBox(String.Format("{0}{4}{1}{4}{2}{4}{3}", _    content1, content2, content3, content4, vbNewLine)) 

In this case, the same padding takes place, but with a period for the padding character. Figure 5-33 shows the result, which is more meaningful than Figure 5-32.

Figure 5-33. The same padding as before, but using periods for padding instead of spaces





Visual Basic 2005 Cookbook(c) Solutions for VB 2005 Programmers
Visual Basic 2005 Cookbook: Solutions for VB 2005 Programmers (Cookbooks (OReilly))
ISBN: 0596101775
EAN: 2147483647
Year: 2006
Pages: 400

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net