I want to be able to repeat a string of text "n" times:
Something like this -
String "X", user input = n, 5 = n, output: XXXXX
I hope this makes sense... (Please be as specific as possible)
I want to be able to repeat a string of text "n" times:
Something like this -
String "X", user input = n, 5 = n, output: XXXXX
I hope this makes sense... (Please be as specific as possible)
str2 = new String(new char[10]).replace("\0", "hello");
note: this answer was originally posted by user102008 here: Simple way to repeat a String in java
To repeat string n number of times we have a repeat method in Stringutils class from Apache commons.In repeat method we can give the String and number of times the string should repeat and the separator which separates the repeated strings.
Ex: StringUtils.repeat("Hello"," ",2);
returns "Hello Hello"
In the above example we are repeating Hello string two times with space as separator. we can give n number of times in 3 argument and any separator in second argument.
A simple loop will do the job:
int n = 10;
String in = "foo";
String result = "";
for (int i = 0; i < n; ++i) {
result += in;
}
or for larger strings or higher values of n
:
int n = 100;
String in = "foobarbaz";
// the parameter to StringBuilder is optional, but it's more optimal to tell it
// how much memory to preallocate for the string you're about to built with it.
StringBuilder b = new StringBuilder(n * in.length());
for (int i = 0; i < n; ++i) {
b.append(in);
}
String result = b.toString();