35

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 = new StringBuilder(n);
for (int i = 0; i < n; ++i)
{
    sb.append(c);
}
String result = sb.toString();

Surely there is some static library function that already does this for me?

3
  • 2
    Possible duplicate: stackoverflow.com/questions/1235179/…
    – JK.
    Aug 18, 2011 at 12:23
  • 1
    and what hinders you to write a static method just like that?
    – Tedil
    Aug 18, 2011 at 12:25
  • 7
    @Tedil: I don't want to reinvent the wheel.
    – foobar
    Aug 18, 2011 at 12:28

10 Answers 10

48
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.

5
  • 4
    It's in single quotes, not a variable. Unless I'm missing something here... I'm a bit groggy today.
    – G_H
    Aug 18, 2011 at 12:29
  • I'm talking about the c in the original question, not in your answer
    – Tedil
    Aug 18, 2011 at 12:31
  • 4
    @Tedil: "Given a character c and a number n [...]"
    – foobar
    Aug 18, 2011 at 12:32
  • Ah, right. Should also work for a Character object thanks to auto-unboxing. I'm assuming it's a char or Character.
    – G_H
    Aug 18, 2011 at 12:34
  • 2
    The Stream approach is indeed not an advantage. But since Java 11, you can use (""+c).repeat(n)
    – Holger
    Jan 25, 2021 at 17:30
25

If you can, use StringUtils from Apache Commons Lang:

StringUtils.repeat("ab", 3);  //"ababab"
1
  • Useful to know: commons-lang3 has a method taking a char instead of a String. The implementation in recent versions effectively does the same as my answer (using Arrays.fill). The version taking a String has a bunch of branching code paths for optimizations. If the input String is of length 1 it ends up calling the method taking a char. The versions before commons-lang3 seem to perform well too. If you happen to have commons-lang on your classpath you may as well use it.
    – G_H
    Jun 25, 2021 at 11:05
17

Google Guava Time!

Strings.repeat("a", 3)

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

7

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

3
  • Your testing methodology is flawed. Use JMH for accurate results. Sep 20, 2017 at 3:15
  • Indeed this is not a perfect benchmark (a perfect benchmark simply doesn't exist) buy it clearly shows how slower the one method is compared with the other.
    – Panayotis
    Sep 27, 2017 at 1:24
  • It is not a huge difference. In relative terms, sure, the second method is almost 5 times as slow. But we're looking at the difference between something that takes about 65 _micro_seconds and something that takes 305 _micro_seconds. It's not even in the millisecond scale. And that's for making a 100000 character String. I would never make a choice based on such microscopic optimizations instead of legibility in Java. Only with the exception if it concerns a piece of code that will be executed many times per second.
    – G_H
    Jun 25, 2021 at 9:21
5

Java SE 11

String#repeat​(int count), introduced as part of Java SE 11, makes it quite easy to do.

Demo:

public class Main {
    public static void main(String[] args) {
        char ch = 'c';
        int n = 20;
        String result = String.valueOf(ch).repeat(n);
        System.out.println(result);
    }
}

Output:

cccccccccccccccccccc
3

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

1

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.

6
  • 5
    This takes O(log N) time assuming that += for String takes O(1) time. I do not think that your assumption is reasonable. Jun 18, 2014 at 23:56
  • 1
    @Tsuyoshi Ito: Good point. Using a pre-sized StringBuilder will get closer to the ideal.
    – rossum
    Jun 19, 2014 at 10:31
  • @TsuyoshiIto You use O() according to a unit operation you define. In that case, += is the unit operation so O(log N) is valid. But you're right pointing that, internally, += will be using a StringBuilder which can have an overhead.
    – Matthieu
    Feb 26, 2016 at 15:24
  • 1
    Seems like this involves copying longer and longer strings on each successive +=. So this algo does more work on each += than the previous. It also creates garbage. So using '+=' as the 'unit' is really not such a good way of looking at it. You are probably better of using a single StringBuilder and loop to add chars one by one. A lot less garbage and string copying will be involved which probably means better performance overall.
    – Kris
    Oct 5, 2016 at 15:52
  • 1
    There is no way to do this in O(log N). If you want to have a string of n repeating characters, it means that n memory locations will have to be filled in with a value. This is O(N) at best. Your algorithm is string concatenation in a loop in disguise. Using a StringBuilder will eventually still come down to linear time at best.
    – G_H
    Oct 3, 2017 at 7:15
0

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.

3
  • 2
    Why are you using Integer instead of int?
    – Jesper
    Aug 18, 2011 at 12:27
  • Personal preference. It doesn't really matter. Aug 18, 2011 at 12:33
  • 11
    @Mike - doesn't matter? Using your own words "That's very wasteful. Every iteration of that for loop will" call intValue (3 times) and valueOf (once/interaction) eventually creating a new Integer (x > 127)!
    – user85421
    Aug 18, 2011 at 12:50
0

I am adding another way to solve it:

public String buildString(Character character, int nTimes) {
    return String.format("%" + nTimes + "s", " ").replace(' ', character);
}
0

If you are not on Java 11+ (otherwise I would go with Arvind Kumar Avinash's answer), you can also combine String#join(CharSequence, Iterable<? extends CharSequence> and Collections#nCopies(int, T):

String result = String.join("", Collections.nCopies(c, n));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.