113

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

Gerold Broser
  • 14,080
  • 5
  • 48
  • 107
Mithrax
  • 7,603
  • 18
  • 55
  • 60

19 Answers19

99

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");
    }
}
bluish
  • 26,356
  • 27
  • 122
  • 180
Andi
  • 1,131
  • 7
  • 2
38

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"
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Naman
  • 27,789
  • 26
  • 218
  • 353
  • 1
    Looking at the implementation [here](https://github.com/openjdk/jdk/blob/master/src/java.base/share/classes/java/lang/String.java#L3560) 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. – joshpetit Jan 03 '21 at 12:31
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);
rogerdpack
  • 62,887
  • 36
  • 269
  • 388
les2
  • 14,093
  • 16
  • 59
  • 76
  • 9
    how come you assumed he is using maven? :) – Bozho Feb 12 '10 at 22:32
  • 5
    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. :) – les2 Feb 12 '10 at 22:56
  • 1
    org.apache.commons commons-lang3 would be more "modern" version – scrutari May 18 '17 at 20:17
27

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

String repeated = Strings.repeat("pete and re", 42);
sebkur
  • 658
  • 2
  • 9
  • 18
Matt Ball
  • 354,903
  • 100
  • 647
  • 710
20

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.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • 3
    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... – hjhill Feb 13 '10 at 09:07
  • 1
    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. – BalusC Feb 13 '10 at 12:30
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);
Dave Hartnoll
  • 1,144
  • 11
  • 21
  • 2
    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 Burcea Sep 13 '13 at 11:11
  • 2
    @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. – Dave Hartnoll Sep 14 '13 at 12:27
  • very pragmatic, I like it – kodu Jun 02 '17 at 09:14
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();
}
Dominik Sandjaja
  • 6,326
  • 6
  • 52
  • 77
Ali Imran
  • 8,927
  • 3
  • 39
  • 50
12

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

Geo
  • 93,257
  • 117
  • 344
  • 520
  • 7
    String multiplyString(String str, int count){ StringBuilder sb = new StringBuilder(); for( int i = 0; i < count; ++i ){ sb.append(str); } return sb.toString(); } – Vincent Robert Feb 12 '10 at 22:33
  • 2
    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. – les2 Feb 12 '10 at 23:03
  • 5
    Chill. He was asking how it could be done. He wasn't asking for a jar. – Geo Feb 14 '10 at 16:51
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);
}
Bohemian
  • 412,405
  • 93
  • 575
  • 722
8

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) : "";
}
Gerold Broser
  • 14,080
  • 5
  • 48
  • 107
niczm25
  • 169
  • 1
  • 2
  • 13
  • 1
    +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). – Gerold Broser Jul 01 '16 at 16:39
5

with Dollar:

String s = "123" + $("0").repeat(3); // 123000
dfa
  • 114,442
  • 31
  • 189
  • 228
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.

Vivin Paliath
  • 94,126
  • 40
  • 223
  • 295
4

With Guava:

Joiner.on("").join(Collections.nCopies(i, someNum));
finnw
  • 47,861
  • 24
  • 143
  • 221
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.

bluish
  • 26,356
  • 27
  • 122
  • 180
Carlos Blanco
  • 8,592
  • 17
  • 71
  • 101
  • 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. – les2 Feb 12 '10 at 23:00
  • 2
    "The first rule of programming should be Don't Write Code." - Ok, you are fired. Programmers are obsolete. LOL – ceklock Dec 09 '12 at 01:47
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);
Dakkaron
  • 5,930
  • 2
  • 36
  • 51
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"

0

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";
}
-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";
}
Michael Myers
  • 188,989
  • 46
  • 291
  • 292
royalsampler
  • 1,195
  • 8
  • 4
-15

The simplest way is:

String someNum = "123000";
System.out.println(someNum);
Pops
  • 30,199
  • 37
  • 136
  • 151
Arbaaz
  • 1
  • 7
    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. – Pops Nov 10 '11 at 15:24
  • 9
    Let's hardcode every possible output of our algorithms. Hardcodes for the wiiin !! – Silviu Burcea Sep 13 '13 at 11:43