Simple way to repeat a string

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

    Despite your desire not to use loops, I think you should use a loop.

    String repeatString(String s, int repetitions)
    {
        if(repetitions < 0) throw SomeException();
    
        else if(s == null) return null;
    
        StringBuilder stringBuilder = new StringBuilder(s.length() * repetitions);
    
        for(int i = 0; i < repetitions; i++)
            stringBuilder.append(s);
    
        return stringBuilder.toString();
    }
    

    Your reasons for not using a for loop are not good ones. In response to your criticisms:

    1. Whatever solution you use will almost certainly be longer than this. Using a pre-built function only tucks it under more covers.
    2. Someone reading your code will have to figure out what you're doing in that non-for-loop. Given that a for-loop is the idiomatic way to do this, it would be much easier to figure out if you did it with a for loop.
    3. Yes someone might add something clever, but by avoiding a for loop you are doing something clever. That's like shooting yourself in the foot intentionally to avoid shooting yourself in the foot by accident.
    4. Off-by-one errors are also mind-numbingly easy to catch with a single test. Given that you should be testing your code, an off-by-one error should be easy to fix and catch. And it's worth noting: the code above does not contain an off-by-one error. For loops are equally easy to get right.
    5. So don't reuse variables. That's not the for-loop's fault.
    6. Again, so does whatever solution you use. And as I noted before; a bug hunter will probably be expecting you to do this with a for loop, so they'll have an easier time finding it if you use a for loop.

提交回复
热议问题