ProblemYou want to create a string of n space characters. SolutionUse the Space(N) function, which returns a string of n space characters. DiscussionThe 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 waysSee AlsoRecipe 5.2 discusses similar functionality. |