A DESCRIPTION OF THE REQUEST :
I'd like an instance method on class String that will repeat the string. E.g., "0".repeat(8) would be "00000000".
Guava and Apache Commons provide this functionality, and several other languages have it as a built-in, which shows it is a commonly wanted feature. A method on class String itself can do it most efficiently, because it can avoid duplicating the array on construction. It is also a more convenient place to have it, rather than having to import string util classes in external libraries.
A suggested implementation, written by me, released to public domain:
/**
* Returns a string that consists of this string repeated some number of times.
*
* @param count the number of times to repeat this string
* @return a string of {@code count} copies of this string
* @throws IllegalArgumentException if {@code count} is negative
*/
public String repeat(int count) {
if (count < 0) throw new IllegalArgumentException("Repeat count is negative");
if (count == 1) return this;
int length = length();
if (count == 0 || length == 0) return "";
if ((long)count * length > Integer.MAX_VALUE)
throw new OutOfMemoryError();
char[] out = new char[count * length];
if (length == 1) {
Arrays.fill(out, value[0]);
} else {
for (int i = 0; i < out.length; i += length)
System.arraycopy(value, 0, out, i, length);
}
return new String(out, true); // uncopied array
}
JUSTIFICATION :
.
I'd like an instance method on class String that will repeat the string. E.g., "0".repeat(8) would be "00000000".
Guava and Apache Commons provide this functionality, and several other languages have it as a built-in, which shows it is a commonly wanted feature. A method on class String itself can do it most efficiently, because it can avoid duplicating the array on construction. It is also a more convenient place to have it, rather than having to import string util classes in external libraries.
A suggested implementation, written by me, released to public domain:
/**
* Returns a string that consists of this string repeated some number of times.
*
* @param count the number of times to repeat this string
* @return a string of {@code count} copies of this string
* @throws IllegalArgumentException if {@code count} is negative
*/
public String repeat(int count) {
if (count < 0) throw new IllegalArgumentException("Repeat count is negative");
if (count == 1) return this;
int length = length();
if (count == 0 || length == 0) return "";
if ((long)count * length > Integer.MAX_VALUE)
throw new OutOfMemoryError();
char[] out = new char[count * length];
if (length == 1) {
Arrays.fill(out, value[0]);
} else {
for (int i = 0; i < out.length; i += length)
System.arraycopy(value, 0, out, i, length);
}
return new String(out, true); // uncopied array
}
JUSTIFICATION :
.
- relates to
-
JDK-8197594 String#repeat
-
- Resolved
-