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

后端 未结 8 1736
时光说笑
时光说笑 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.

    0 讨论(0)
  • 2020-12-15 16:52

    Google Guava Time!

    Strings.repeat("a", 3)
    

    http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/Strings.html

    0 讨论(0)
  • 2020-12-15 16:59

    To have an idea of the speed penalty, I have tested two versions, one with Array.fill and one with StringBuilder.

    public static String repeat(char what, int howmany) {
        char[] chars = new char[howmany];
        Arrays.fill(chars, what);
        return new String(chars);
    }
    

    and

    public static String repeatSB(char what, int howmany) {
        StringBuilder out = new StringBuilder(howmany);
        for (int i = 0; i < howmany; i++)
            out.append(what);
        return out.toString();
    }
    

    using

    public static void main(String... args) {
        String res;
        long time;
    
        for (int j = 0; j < 1000; j++) {
            res = repeat(' ', 100000);
            res = repeatSB(' ', 100000);
        }
        time = System.nanoTime();
        res = repeat(' ', 100000);
        time = System.nanoTime() - time;
        System.out.println("elapsed repeat: " + time);
    
        time = System.nanoTime();
        res = repeatSB(' ', 100000);
        time = System.nanoTime() - time;
        System.out.println("elapsed repeatSB: " + time);
    }
    

    (note the loop in main function is to kick in JIT)

    The results are as follows:

    elapsed repeat  : 65899
    elapsed repeatSB: 305171
    

    It is a huge difference

    0 讨论(0)
  • 2020-12-15 16:59
    string result = new StringBuilder().Append('c', n).ToString();
    
    0 讨论(0)
  • 2020-12-15 17:02

    take look at this sample

    Integer  n=10;
    String s="a";
    String repeated = new String(new char[n]).replace("\0", s);
    

    answer taken form Simple way to repeat a String in java so vote up there

    0 讨论(0)
  • 2020-12-15 17:04

    If you can, use StringUtils from Apache Commons Lang:

    StringUtils.repeat("ab", 3);  //"ababab"
    
    0 讨论(0)
提交回复
热议问题