ProblemYou want a string comprised of a sequence of characters repeated many times. For example, you want to create a fancy separator string comprised of alternating "+" and "~" characters, as shown in Figure 5-2. Figure 5-2. A string formed by repeating two characters many timesSolutionUse a StringBuilder to append as many copies of the string as desired. Then convert the result to a true string using the StringBuilder's ToString() method: Dim fancyString As New System.Text.StringBuilder For counter As Integer = 1 To 35 fancyString.Append("+~") Next counter MsgBox(fancyString.ToString()) DiscussionStrings in .NET are immutable, which means that once they've been created, they sit in one spot in memory and can never be modified. All functions that might appear to be changing a string's contents are actually making new copies of the original string, modified en route. In most cases, immutability provides superior string handling and processing capabilities, but when it comes to concatenating strings, the speed and efficiency advantages are nullified. The StringBuilder object solves the concatenation dilemma nicely. It allows dynamic, in-place modification of a buffer containing a sequence of string characters, without the need to constantly reallocate String objects. If the allocated buffer space runs out, the StringBuilder efficiently and automatically doubles the number of bytes for its character workspace, and it will do so as many times as are required to handle the strings and characters appended to it. See AlsoRecipe 5.27 shows how the StringBuilder alternative really is faster than standard string concatenation. |