Here you can find the source of repeat(String string, int times)
Parameter | Description |
---|---|
string | The string to be copied. |
repeat | The number of times to repeat the given string. |
Parameter | Description |
---|---|
IllegalArgumentException | if argument <tt>times</tt> is < 0 or passed string is null |
public static final String repeat(String string, int times)
//package com.java2s; /*//from ww w . j ava2s .com * EuroCarbDB, a framework for carbohydrate bioinformatics * * Copyright (c) 2006-2009, Eurocarb project, or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * A copy of this license accompanies this distribution in the file LICENSE.txt. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * Last commit: $Rev: 1593 $ by $Author: hirenj $ on $Date:: 2009-08-14 #$ */ import java.util.Arrays; public class Main { /************************************************** * * Returns a string that is formed by the repetition of a provided * string a given number of times. * * @param string * The string to be copied. * @param repeat * The number of times to repeat the given string. * @return * The joined string. * @throws IllegalArgumentException * if argument <tt>times</tt> is < 0 or passed string is null */ public static final String repeat(String string, int times) { if (times < 0) throw new IllegalArgumentException("Argument 'times' cannot be less than 0"); if (string == null) throw new IllegalArgumentException("Argument 'string' cannot be null"); if (times == 1) return string; if (times == 0 || string.length() == 0) return ""; StringBuilder sb = new StringBuilder(string.length() * times); while (times-- > 0) sb.append(string); return sb.toString(); } /************************************************** * * Returns a string that is formed by the repetition of the given * <tt>char</tt> the given number of times, eg: *<pre> * // returns "aaaaa" * repeat('a', 5 ); </pre> */ public static final String repeat(char c, int times) { if (times < 0) throw new IllegalArgumentException("Argument 'times' cannot be less than 0"); if (times == 0) return ""; if (times == 1) return Character.toString(c); char[] chars = new char[times]; Arrays.fill(chars, c); return new String(chars); } }