Simple way to repeat a string

后端 未结 30 3539
清酒与你
清酒与你 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:12

    If speed is your concern, then you should use as less memory copying as possible. Thus it is required to work with arrays of chars.

    public static String repeatString(String what, int howmany) {
        char[] pattern = what.toCharArray();
        char[] res = new char[howmany * pattern.length];
        int length = pattern.length;
        for (int i = 0; i < howmany; i++)
            System.arraycopy(pattern, 0, res, i * length, length);
        return new String(res);
    }
    

    To test speed, a similar optimal method using StirngBuilder is like this:

    public static String repeatStringSB(String what, int howmany) {
        StringBuilder out = new StringBuilder(what.length() * howmany);
        for (int i = 0; i < howmany; i++)
            out.append(what);
        return out.toString();
    }
    

    and the code to test it:

    public static void main(String... args) {
        String res;
        long time;
    
        for (int j = 0; j < 1000; j++) {
            res = repeatString("123", 100000);
            res = repeatStringSB("123", 100000);
        }
    
        time = System.nanoTime();
        res = repeatString("123", 1000000);
        time = System.nanoTime() - time;
        System.out.println("elapsed repeatString: " + time);
    
        time = System.nanoTime();
        res = repeatStringSB("123", 1000000);
        time = System.nanoTime() - time;
        System.out.println("elapsed repeatStringSB: " + time);
    
    }
    

    And here the run results from my system:

    elapsed repeatString: 6006571
    elapsed repeatStringSB: 9064937
    

    Note that the test for loop is to kick in JIT and have optimal results.

提交回复
热议问题