Can I multiply strings in Java to repeat sequences? [duplicate]

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 1:

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

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

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("\0", 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");
    }
}

Solution 2:

No, but you can in Scala! (And then compile that and run it using any Java implementation!!!!)

Now, if you want to do it the easy way in java, use the Apache commons-lang package. Assuming you're using maven, add this dependency to your pom.xml:

    <dependency>
        <groupId>commons-lang</groupId>
        <artifactId>commons-lang</artifactId>
        <version>2.4</version>
    </dependency>

And then use StringUtils.repeat as follows:

import org.apache.commons.lang.StringUtils
...
someNum = sumNum + StringUtils.repeat("0", 3);

Solution 3:

Google Guava provides another way to do this with Strings#repeat():

String repeated = Strings.repeat("pete and re", 42);