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?

foobar
  • 4,968
  • 3
  • 17
  • 11

11 Answers11

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.

G_H
  • 11,739
  • 3
  • 38
  • 82
  • 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 '11 at 12:29
  • I'm talking about the c in the original question, not in your answer – Tedil Aug 18 '11 at 12:31
  • 4
    @Tedil: "Given a **character** c and a number n [...]" – foobar Aug 18 '11 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 '11 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 '21 at 17:30
25

If you can, use StringUtils from Apache Commons Lang:

StringUtils.repeat("ab", 3);  //"ababab"
jake stayman
  • 1,687
  • 13
  • 22
Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
  • 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 '21 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

Jeremy
  • 22,188
  • 4
  • 68
  • 81
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

Matthieu
  • 2,736
  • 4
  • 57
  • 87
Panayotis
  • 1,792
  • 23
  • 32
  • Your testing methodology is flawed. Use JMH for accurate results. – Craig P. Motlin Sep 20 '17 at 03: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 '17 at 01: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 '21 at 09: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
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
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

Community
  • 1
  • 1
Basheer AL-MOMANI
  • 14,473
  • 9
  • 96
  • 92
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.

rossum
  • 15,344
  • 1
  • 24
  • 38
  • 5
    This takes O(log N) time assuming that `+=` for String takes O(1) time. I do not think that your assumption is reasonable. – Tsuyoshi Ito Jun 18 '14 at 23:56
  • 1
    @Tsuyoshi Ito: Good point. Using a pre-sized StringBuilder will get closer to the ideal. – rossum Jun 19 '14 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 '16 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 05 '16 at 15:52
  • See my response to @Tsuyoshi Ito. A pre-sized `StringBuilder` will remove a lot of the overhead by allocating all the space needed at the start. – rossum Oct 05 '16 at 17:05
  • 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 03 '17 at 07:15
0

I am adding another way to solve it:

public String buildString(Character character, int nTimes) {
    return String.format("%" + nTimes + "s", " ").replace(' ', character);
}
Fabio Mendes Soares
  • 1,357
  • 5
  • 20
  • 30
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));
beatngu13
  • 7,201
  • 6
  • 37
  • 66
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.

Mike Thomsen
  • 36,828
  • 10
  • 60
  • 83
0

A simple and clean solution would be to use String.format and then replace characters with desired character.

String.format("%5s", "").replace(' ', '#')
// Output : #####

If you are using Java 11

you can just use String.repeat()

"#".repeat(5)
afzalex
  • 8,598
  • 2
  • 34
  • 61