repeat string for certain times - Android java.lang

Android examples for java.lang:String Algorithm

Description

repeat string for certain times

Demo Code

public class Main{

    /**/*from   w w w. j a v  a  2s  .  c om*/
     * <pre>
     * StringUtil.repeat(null, *)   = null
     * StringUtil.repeat("", -1)    = ""
     * StringUtil.repeat("", 2)     = ""
     * StringUtil.repeat("han", -1) = ""
     * StringUtil.repeat("han", 0)  = ""
     * StringUtil.repeat("han", 2)  = "hanhan"
     * </pre>
     * 
     */
    public static String repeat(String str, int repeat) {
        if (str == null) {
            return null;
        }
        if (repeat < 1) {
            return "";
        }
        int inputLen = str.length();
        if (inputLen == 0 || repeat == 1) {
            return str;
        }
        int outputLen = inputLen * repeat;
        if (inputLen == 1) {
            char ch = str.charAt(0);
            char[] output = new char[outputLen];
            for (int i = 0; i < outputLen; i++) {
                output[i] = ch;
            }
            return new String(output);
        } else {
            StringBuilder output = new StringBuilder((int) Math.min(
                    (outputLen * 110L) / 100, Integer.MAX_VALUE));
            for (int i = 0; i < repeat; i++) {
                output.append(str);
            }
            return output.toString();
        }
    }

}

Related Tutorials