What is the easiest way to generate a String of n repeated characters?
If you can, use StringUtils from Apache Commons Lang:
StringUtils.repeat("ab", 3); //"ababab"
Google Guava Time!
Strings.repeat("a", 3)
http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/Strings.html
int n = 10;
char[] chars = new char[n];
Arrays.fill(chars, 'c');
String result = new String(chars);
EDIT:
It's been 9 years since this answer was submitted but it still attracts some attention now and then. In the meantime Java 8 has been introduced with functional programming features. Given a char c
and the desired number of repetitions count
the following one-liner can do the same as above.
String result = IntStream.range(1, count).mapToObj(index -> "" + c).collect(Collectors.joining());
Do note however that it is slower than the array approach. It should hardly matter in any but the most demanding circumstances. Unless it's in some piece of code that will be executed thousands of times per second it won't make much difference. This can also be used with a String instead of a char to repeat it a number of times so it's a bit more flexible. No third-party libraries needed.
To have an idea of the speed penalty, I have tested two versions, one with Array.fill and one with StringBuilder.
public static String repeat(char what, int howmany) {
char[] chars = new char[howmany];
Arrays.fill(chars, what);
return new String(chars);
}
and
public static String repeatSB(char what, int howmany) {
StringBuilder out = new StringBuilder(howmany);
for (int i = 0; i < howmany; i++)
out.append(what);
return out.toString();
}
using
public static void main(String... args) {
String res;
long time;
for (int j = 0; j < 1000; j++) {
res = repeat(' ', 100000);
res = repeatSB(' ', 100000);
}
time = System.nanoTime();
res = repeat(' ', 100000);
time = System.nanoTime() - time;
System.out.println("elapsed repeat: " + time);
time = System.nanoTime();
res = repeatSB(' ', 100000);
time = System.nanoTime() - time;
System.out.println("elapsed repeatSB: " + time);
}
(note the loop in main function is to kick in JIT)
The results are as follows:
elapsed repeat : 65899
elapsed repeatSB: 305171
It is a huge difference