Given a character c and a number n, how can I create a String that consists of n repetitions of c? Doing it manually is too cumbersome:
StringBuilder sb = ne
Here is an O(logN) method, based on the standard binary powering algorithm:
public static String repChar(char c, int reps) {
String adder = Character.toString(c);
String result = "";
while (reps > 0) {
if (reps % 2 == 1) {
result += adder;
}
adder += adder;
reps /= 2;
}
return result;
}
Negative values for reps
return the empty string.
Google Guava Time!
Strings.repeat("a", 3)
http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/Strings.html
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
string result = new StringBuilder().Append('c', n).ToString();
take look at this sample
Integer n=10;
String s="a";
String repeated = new String(new char[n]).replace("\0", s);
answer taken form Simple way to repeat a String in java so vote up there
If you can, use StringUtils from Apache Commons Lang:
StringUtils.repeat("ab", 3); //"ababab"