Simple way to repeat a string

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

    I really enjoy this question. There is a lot of knowledge and styles. So I can't leave it without show my rock and roll ;)

    {
        String string = repeat("1234567890", 4);
        System.out.println(string);
        System.out.println("=======");
        repeatWithoutCopySample(string, 100000);
        System.out.println(string);// This take time, try it without printing
        System.out.println(string.length());
    }
    
    /**
     * The core of the task.
     */
    @SuppressWarnings("AssignmentToMethodParameter")
    public static char[] repeat(char[] sample, int times) {
        char[] r = new char[sample.length * times];
        while (--times > -1) {
            System.arraycopy(sample, 0, r, times * sample.length, sample.length);
        }
        return r;
    }
    
    /**
     * Java classic style.
     */
    public static String repeat(String sample, int times) {
        return new String(repeat(sample.toCharArray(), times));
    }
    
    /**
     * Java extreme memory style.
     */
    @SuppressWarnings("UseSpecificCatch")
    public static void repeatWithoutCopySample(String sample, int times) {
        try {
            Field valueStringField = String.class.getDeclaredField("value");
            valueStringField.setAccessible(true);
            valueStringField.set(sample, repeat((char[]) valueStringField.get(sample), times));
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }
    

    Do you like it?

提交回复
热议问题