Recipe 5.2. Creating a String of N Identical Characters


You need to create a string comprised of a single character repeated many times. These strings are sometimes useful in the formatting of ASCII text for display or printed output.


Create a new string of repeated characters using the String class itself. One of its overloaded constructors accepts a character to repeat and a repetition count.


Most of the time you create string variables using the default constructor, which initializes the variables to Nothing. This is why you must assign a string value to a string variable after creating it, but before using its contents. However, you can use over-loaded versions of the string constructor to assign string data immediately upon creation. One version of the string constructor takes a character and a count and efficiently builds a string by repeating the character the given number of times. The following statement builds a string of 72 asterisks:

 Dim lotsOfAsterisks As New String("*"c, 72) 

Visual Basic 2005 also provides a second way to create strings of duplicated characters. The StrDup() function, which is very similar to the original String() function found in Visual Basic 6, does the trick:

 lotsOfAsterisks = StrDup(72, "*") 

Notice the difference in the order of the parameters between the string constructor syntax and the function call. Fortunately, Visual Studio's IntelliSense means you don't have to memorize the order of the parameters.

VB 6 Users' Update

The VB 6 String() function returns a string based on a count and the first character of the string:

 lotsOfAsterisks = String(72, "*") 

Most sources mention only the new String constructor technique to create strings of duplicate characters in Visual Basic 2005, but after doing a lot of timing tests, we've seen that the StrDup() function is very nearly identical in speed and efficiency. Also, its syntax is much more like that of the original VB 6 String() function. Use whichever technique suits you better.

See Also

Recipe 5.45 demonstrates another method of creating strings of a common character.

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 © 2008-2017.
If you may any questions please contact us: