< prev index next >

src/java.base/share/classes/java/lang/String.java

Print this page
rev 49004 : 8197594: String#repeat

*** 2961,2970 **** --- 2961,3016 ---- * guaranteed to be from a pool of unique strings. * @jls 3.10.5 String Literals */ public native String intern(); + /** + * Returns a string whose value is the concatenation of this + * string repeated {@code count} times. + * <p> + * If count or length is zero then the empty string is returned. + * <p> + * This method may be used to create space padding for + * formatting text or zero padding for formatting numbers. + * @param count number of times to repeat + * @return A string composed of this string repeated + * {@code count} times or the empty string if count + * or length is zero. + * @throws IllegalArgumentException if the {@code count} is + * negative. + */ + public String repeat(int count) { + if (count < 0) { + throw new IllegalArgumentException("count is negative, " + count); + } + if (count == 1) { + return this; + } + final int len = value.length; + if (len == 0 || count == 0) { + return ""; + } + if (len == 1) { + final byte[] single = new byte[count]; + Arrays.fill(single, value[0]); + return new String(single, coder); + } + if (Integer.MAX_VALUE / count < len) { + throw new OutOfMemoryError(); + } + final int limit = len * count; + final byte[] multiple = new byte[limit]; + System.arraycopy(value, 0, multiple, 0, len); + int copied = len; + for (int next = copied << 1; next < limit && 0 < next; next = next << 1) { + System.arraycopy(multiple, 0, multiple, copied, copied); + copied = next; + } + System.arraycopy(multiple, 0, multiple, copied, limit - copied); + return new String(multiple, coder); + } + //////////////////////////////////////////////////////////////// /** * Copy character bytes from this string into dst starting at dstBegin. * This method doesn't perform any range checking.
< prev index next >