What is the easiest way to generate a String of n repeated characters?

后端 未结 8 1744
时光说笑
时光说笑 2020-12-15 16:25

Given a character c and a number n, how can I create a String that consists of n repetitions of c? Doing it manually is too cumbersome:

StringBuilder sb = ne         


        
8条回答
  •  心在旅途
    2020-12-15 16:51

    Here is an O(logN) method, based on the standard binary powering algorithm:

    public static String repChar(char c, int reps) {
        String adder = Character.toString(c);
        String result = "";
        while (reps > 0) {
            if (reps % 2 == 1) {
                result += adder;
            }
            adder += adder;
            reps /= 2;
        }        
        return result;
    }
    

    Negative values for reps return the empty string.

提交回复
热议问题