The easiest way in plain Java with no dependencies is the following one-liner:
new String(new char[generation]).replace("", "-")
Replace generation with number of repetitions, and the "-" with the string (or char) you want repeated.
All this does is create an empty string containing n number of 0x00 characters, and the built-in String#replace method does the rest.
Here's a sample to copy and paste:
public static String repeat(int count, String with) {
return new String(new char[count]).replace("", with);
}
public static String repeat(int count) {
return repeat(count, " ");
}
public static void main(String[] args) {
for (int n = 0; n < 10; n++) {
System.out.println(repeat(n) + " Hello");
}
for (int n = 0; n < 10; n++) {
System.out.println(repeat(n, ":-) ") + " Hello");
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…