Recipe 5.3. Creating a String by Repeating a String N Times


Problem

You 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 times


Solution

Use 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()) 

Discussion

Strings 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 Also

Recipe 5.27 shows how the StringBuilder alternative really is faster than standard string concatenation.




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