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

后端 未结 8 1737
时光说笑
时光说笑 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 17:08

    Just add it to your own...

    public static String generateRepeatingString(char c, Integer n) {
        StringBuilder b = new StringBuilder();
        for (Integer x = 0; x < n; x++)
            b.append(c);
        return b.toString();
    }
    

    Or Apache commons has a utility class you can add.

    0 讨论(0)
  • 2020-12-15 17:13
    int n = 10;
    char[] chars = new char[n];
    Arrays.fill(chars, 'c');
    String result = new String(chars);
    

    EDIT:

    It's been 9 years since this answer was submitted but it still attracts some attention now and then. In the meantime Java 8 has been introduced with functional programming features. Given a char c and the desired number of repetitions count the following one-liner can do the same as above.

    String result = IntStream.range(1, count).mapToObj(index -> "" + c).collect(Collectors.joining());
    

    Do note however that it is slower than the array approach. It should hardly matter in any but the most demanding circumstances. Unless it's in some piece of code that will be executed thousands of times per second it won't make much difference. This can also be used with a String instead of a char to repeat it a number of times so it's a bit more flexible. No third-party libraries needed.

    0 讨论(0)
提交回复
热议问题