Simple way to repeat a string

后端 未结 30 3034
清酒与你
清酒与你 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 06:59

    Using recursion, you can do the following (using ternary operators, one line max):

    public static final String repeat(String string, long number) {
        return number == 1 ? string : (number % 2 == 0 ? repeat(string + string, number / 2) : string + repeat(string + string, (number - 1) / 2));
    }
    

    I know, it's ugly and probably not efficient, but it's one line!

提交回复
热议问题