Simple way to repeat a string

后端 未结 30 3040
清酒与你
清酒与你 2020-11-21 06:55

I\'m looking for a simple commons method or operator that allows me to repeat some string n times. I know I could write this using a for loop, but I wish to avoid f

30条回答
  •  离开以前
    2020-11-21 07:01

    using only JRE classes (System.arraycopy) and trying to minimize the number of temp objects you can write something like:

    public static String repeat(String toRepeat, int times) {
        if (toRepeat == null) {
            toRepeat = "";
        }
    
        if (times < 0) {
            times = 0;
        }
    
        final int length = toRepeat.length();
        final int total = length * times;
        final char[] src = toRepeat.toCharArray();
        char[] dst = new char[total];
    
        for (int i = 0; i < total; i += length) {
            System.arraycopy(src, 0, dst, i, length);
        }
    
        return String.copyValueOf(dst);
    }
    

    EDIT

    and without loops you can try with:

    public static String repeat2(String toRepeat, int times) {
        if (toRepeat == null) {
            toRepeat = "";
        }
    
        if (times < 0) {
            times = 0;
        }
    
        String[] copies = new String[times];
        Arrays.fill(copies, toRepeat);
        return Arrays.toString(copies).
                  replace("[", "").
                  replace("]", "").
                  replaceAll(", ", "");
    }
    

    EDIT 2

    using Collections is even shorter:

    public static String repeat3(String toRepeat, int times) {
        return Collections.nCopies(times, toRepeat).
               toString().
               replace("[", "").
               replace("]", "").
               replaceAll(", ", "");
    }
    

    however I still like the first version.

提交回复
热议问题