119

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

2

19 Answers 19

102

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");
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Nice trick! One liners are always great..
I was looking for this since years and now I finally found it.
For me it only worked with "\u0000" instead of "\0"
47

String::repeat

Use String::repeat in Java 11 and later.

Examples

"A".repeat( 3 ) 

AAA

And the example from the Question.

int i = 3; //frequency to repeat
String someNum = "123"; // initial string
String ch = "0"; // character to append

someNum = someNum + ch.repeat(i); // formulation of the string
System.out.println(someNum); // would result in output -- "123000"

1 Comment

Looking at the implementation here what is the time complexity? I'm debating whether it makes more sense to use a while loop and a string builder if the string builder is already created and in use.
36

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);

3 Comments

how come you assumed he is using maven? :)
You have to make some assumptions in order to solve real world problems. In this case, I'm using maven on my current project. I have a pom.xml set up with the commons-lang dependency. It made it easier for me to answer his question, in short. And I'm not exactly sure what I'd do if I wasn't using maven - I guess I'd have to create a custom location for my jar files ... similar to a maven repository! And then include those jar files on my classpath and do all kinds of work I like to avoid. If the poster really wants to hack java, then she or he needs to use maven or its equivalent. :)
<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> </dependency> would be more "modern" version
27

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

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

Comments

21

Two ways comes to mind:

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

// Way 1:
char[] zeroes1 = new char[i];
Arrays.fill(zeroes1, '0');
String newNum1 = someNum + new String(zeroes1);
System.out.println(newNum1); // 123000

// Way 2:
String zeroes2 = String.format("%0" + i + "d", 0);
String newNum2 = someNum + zeroes2;
System.out.println(newNum2); // 123000

Way 2 can be shortened to:

someNum += String.format("%0" + i + "d", 0);
System.out.println(someNum); // 123000

More about String#format() is available in its API doc and the one of java.util.Formatter.

2 Comments

Way 1 only works with single characters, Way 2 only works with a single '0'. Not exactly what I'd call a generic solution to the problem...
Not sure what you're talking about, but it's at least a suitable solution for the OP's own problem :) If you have a problem, ask a question.
19

If you're repeating single characters like the OP, and the maximum number of repeats is not too high, then you could use a simple substring operation like this:

int i = 3;
String someNum = "123";
someNum += "00000000000000000000".substring(0, i);

3 Comments

This is not a general answer if you ask me, if I wanted to do "123" * 3, your solution won't work. Ok, this is elegant for single chars, but it's not flexible :)
@Silviu It's not a general answer if you ask anyone, and no-one asked for a general answer. My opening comments cover the cases it works for, including the OP's case.
very pragmatic, I like it
12

No. Java does not have this feature. You'd have to create your String using a StringBuilder, and a loop of some sort.

3 Comments

String multiplyString(String str, int count){ StringBuilder sb = new StringBuilder(); for( int i = 0; i < count; ++i ){ sb.append(str); } return sb.toString(); }
StringUtils has been performance tuned and tested. The time to produce a production quality String utility library is time you don't have unless your current project is to write a production quality String utility library. Don't write code you don't have to. Plus, there are many other useful methods in StringUtils and commons-lang you can use. It's worth the dependency.
Chill. He was asking how it could be done. He wasn't asking for a jar.
12

Simple way of doing this.

private String repeatString(String s,int count){
    StringBuilder r = new StringBuilder();
    for (int i = 0; i < count; i++) {
        r.append(s);
    }
    return r.toString();
}

3 Comments

Why was this downvoted? This is what I would've done. It seems really simle!
Should really use a StringBuilder. String concatenation like this is rather expensive.
I added the StringBuilder.
10

Java 8 provides a way (albeit a little clunky). As a method:

public static String repeat(String s, int n) {
    return Stream.generate(() -> s).limit(n).collect(Collectors.joining(""));
}

or less efficient, but nicer looking IMHO:

public static String repeat(String s, int n) {
    return Stream.generate(() -> s).limit(n).reduce((a, b) -> a + b);
}

Comments

9

I created a method that do the same thing you want, feel free to try this:

public String repeat(String s, int count) {
    return count > 0 ? s + repeat(s, --count) : "";
}

1 Comment

+1. Recursions are always nice. And this is the shortest that works natively in a Groovy Jenkinsfile or a Jenkins Pipeline project's Groovy script (I tweaked it a bit, with your anticipated permit).
6

with Dollar:

String s = "123" + $("0").repeat(3); // 123000

Comments

4

I don't believe Java natively provides this feature, although it would be nice. I write Perl code occasionally and the x operator in Perl comes in really handy for repeating strings!

However StringUtils in commons-lang provides this feature. The method is called repeat(). Your only other option is to build it manually using a loop.

Comments

4

With Guava:

Joiner.on("").join(Collections.nCopies(i, someNum));

2 Comments

Can't you just use String.join and java.util.Collections.nCopies?
@SolomonUcko yes, in Java 8. (The latest version was 6 when I posted this.)
2

No, you can't. However you can use this function to repeat a character.

public String repeat(char c, int times){
    StringBuffer b = new StringBuffer();

    for(int i=0;i &lt; times;i++){
        b.append(c);
    }

    return b.toString();
}

Disclaimer: I typed it here. Might have mistakes.

2 Comments

The version of repeat in StringUtils has been performance tested on different JVMS. E.g., inspection of it's source code reveals the following comment: "// Performance tuned for 2.0 (JDK1.4)". Now if you look at the implementation, it's pretty hairy - it has all sorts of checks for null and empty String and other optimizations. And it's presumably covered by comprehensive unit tests. The first rule of programming should be Don't Write Code.
"The first rule of programming should be Don't Write Code." - Ok, you are fired. Programmers are obsolete. LOL
1

A generalisation of Dave Hartnoll's answer (I am mainly taking the concept ad absurdum, maybe don't use that in anything where you need speed). This allows one to fill the String up with i characters following a given pattern.

int i = 3;
String someNum = "123";
String pattern = "789";
someNum += "00000000000000000000".replaceAll("0",pattern).substring(0, i);

If you don't need a pattern but just any single character you can use that (it's a tad faster):

int i = 3;
String someNum = "123";
char c = "7";
someNum += "00000000000000000000".replaceAll("0",c).substring(0, i);

Comments

1

Similar to what has already been said:

public String multStuff(String first, String toAdd, int amount) { 
    String append = "";
    for (int i = 1; i <= amount; i++) {
        append += toAdd;               
    }
    return first + append;
}

Input multStuff("123", "0", 3);

Output "123000"

1 Comment

Why not just do i = 0 and i < amount?
-1

There's no shortcut for doing this in Java like the example you gave in Python.

You'd have to do this:

for (;i > 0; i--) {
    somenum = somenum + "0";
}

1 Comment

You might want to use StringBuffer when concatenating string several times.
-1

we can create multiply strings using * in python but not in java you can use for loop in your case:

String sample="123";
for(int i=0;i<3;i++)
{
sample=+"0";
}

Comments

-15

The simplest way is:

String someNum = "123000";
System.out.println(someNum);

2 Comments

Technically, yes, this displays the string the OP used as an example, but it completely misses the string manipulation issue that he was really asking about.
Let's hardcode every possible output of our algorithms. Hardcodes for the wiiin !!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.