Fill a String with Characters
Sometimes you need a string that's filled with a specific number of characters. There are lots of ways to do that but the easiest is to use the New keyword with the String class because the New keyword gives you access to the String object's constructors.
In fact, the String class has three constructors. The first one initializes the string with whatever you pass to the constructor. This one initializes the string to four equals signs:
x = New String("====")
Of course, that's not much of an improvement over what you'd do normally:
X = "===="
But the second constructor is more useful because it accepts a character, an integer and then repeats the character the number of times specified by the integer. This example initializes the string with however may equals signs are specified by initCount:
x = New String("=", initCount)
The third constructor is the most interesting, though I doubt that I'll ever use it. The third constructor lets you initialize the string with a set of characters from a Char array beginning at some point in the array and for some number of characters. This example initializes the string with the digits from 123456789, starting at the position specified in initStart and for the length specified in initLength:
x = New String("123456789", initStart, initLength)
If initStart was set to 2 and initLength was set to 4 then x would be set to "3456".
Posted by Peter Vogel on 02/09/2015