Can I multiply strings in Java to repeat sequences?

By | June 29, 2019

Question

I have something like the following:

int i = 3;
String someNum = "123";

I’d like to append i “0”s to the someNum string. Does it have some way I can multiply a string to repeat it like Python does?

So I could just go:

someNum = sumNum + ("0" * 3);

or something similar?

Where, in this case, my final result would be:

“123000”.

Solution

The easiest way in plain Java with no dependencies is the following one-liner:

new String(new char[generation]).replace("", "-")

Replace generation with number of repetitions, and the “-” with the string (or char) you want repeated.

All this does is create an empty string containing n number of 0x00 characters, and the built-in String#replace method does the rest.

Here’s a sample to copy and paste:

public static String repeat(int count, String with) {
    return new String(new char[count]).replace("", with);
}

public static String repeat(int count) {
    return repeat(count, " ");
}

public static void main(String[] args) {
    for (int n = 0; n < 10; n++) {
        System.out.println(repeat(n) + " Hello");
    }

    for (int n = 0; n < 10; n++) {
        System.out.println(repeat(n, ":-) ") + " Hello");
    }
}

Rate this post

Leave a Reply

Your email address will not be published. Required fields are marked *