Recipe 5.45. Creating a String of Space Characters


Problem

You want to create a string of n space characters.

Solution

Use the Space(N) function, which returns a string of n space characters.

Discussion

The following sample code actually presents three different ways to create a string of n spaces. In most cases the Space() function works quite well to create the spaces, but it's informative to compare the three techniques:

 Dim lotsOfSpaces1 As String = New String(" "c, 500) Dim lotsOfSpaces2 As String = StrDup(500, " "c) Dim lotsOfSpaces3 As String = Space(500) Dim result As String = String.Format( _    "Length of lotsOfSpaces1: {0}{3}" & _    "Length of lotsOfSpaces2: {1}{3}" & _    "Length of lotsOfSpaces3: {2}{3}", _    lotsOfSpaces1.Length, _    lotsOfSpaces2.Length, _    lotsOfSpaces3.Length, vbNewLine) MsgBox(result) 

The String constructor is overloaded to initialize strings as they are created in several ways. As shown in the first statement above, you can create a new string comprised of n repetitions of any character (in this case, a space character).

The StrDup() function is similar in operation in that it also returns a string comprised of n occurrences of a given character. Both the String constructor and the StrDup() function are useful when the repeated character is something other than a space.

Finally, the Space() function returns a string comprised of n space characters, without the option to use any other character.

The rest of the code displays the lengths of the three strings of spaces to help verify that they were created as indicated, as shown in Figure 5-53.

Figure 5-53. Three identical long strings of spaces created in three different ways


See Also

Recipe 5.2 discusses similar functionality.




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

Similar book on Amazon

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