is there a nice way for creating a string initialized with a number of characters given an int (counter) and the character to set. Simply put I would like a method that returns "#,#,#,#,#" when passed 5 and # as parameter.
Any ideas?
Using the StringUtils utility in the Apache Commons lang library:
String myString = StringUtils.repeat("#", ",", 5);
If you only want the characters (and not the comma separators), it is just:
String myString = StringUtils.repeat("#", 5);
It's pretty simple to write a method for this:
public static String createPlaceholderString(char placeholder, int count) {
StringBuilder builder = new StringBuilder(count * 2 - 1);
for (int i = 0; i < count; i++) {
if (i!= 0) {
builder.append(',');
}
builder.append(placeholder);
}
return builder.toString();
}
(Note that we can initialize the builder with exactly the right size of buffer as we know how big it will be.)
You could use something like Strings.repeat from Guava:
String text = Strings.repeat("#,", count - 1) + "#";
Or even more esoterically:
String text = Joiner.on(',').join(Iterables.limit(Iterables.cycle("#"), count));
... but personally I'd probably stick with the method.