Simple way to repeat a string

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

    If you only know the length of the output string (and it may be not divisible by the length of the input string), then use this method:

    static String repeat(String s, int length) {
        return s.length() >= length ? s.substring(0, length) : repeat(s + s, length);
    }
    

    Usage demo:

    for (int i = 0; i < 50; i++)
        System.out.println(repeat("_/‾\\", i));
    

    Don't use with empty s and length > 0, since it's impossible to get the desired result in this case.

提交回复
热议问题