Simple way to repeat a string
If you are using Java <= 7, this is as "concise" as it gets:
// create a string made up of n copies of string sString.format("%0" + n + "d", 0).replace("0", s);
In Java 8 and above there is a more readable way:
// create a string made up of n copies of string sString.join("", Collections.nCopies(n, s));
Finally, for Java 11 and above, there is a new repeat​(int count)
method specifically for this purpose(link)
"abc".repeat(12);
Alternatively, if your project uses java libraries there are more options.
For Apache Commons:
StringUtils.repeat("abc", 12);
For Google Guava:
Strings.repeat("abc", 12);
String::repeat
". ".repeat(7) // Seven period-with-space pairs: . . . . . . .
New in Java 11 is the method String::repeat
that does exactly what you asked for:
String str = "abc";String repeated = str.repeat(3);repeated.equals("abcabcabc");
Its Javadoc says:
/** * Returns a string whose value is the concatenation of this * string repeated {@code count} times. * <p> * If this string is empty or count is zero then the empty * string is returned. * * @param count number of times to repeat * * @return A string composed of this string repeated * {@code count} times or the empty string if this * string is empty or count is zero * * @throws IllegalArgumentException if the {@code count} is * negative. * * @since 11 */