我可以在 Java 中用字符串相乘来重复序列吗?

我有这样的东西:

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

我想将 i“0”附加到 someNum字符串。它有没有什么方法可以让我像 Python 那样乘以一个字符串来重复它呢?

所以我可以说:

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

或者类似的东西?

在这种情况下,我的最终结果是:

“123000”。

214179 次浏览

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

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

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.

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";
}

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.

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.

With Guava:

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

with Dollar:

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

The simplest way is:

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

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

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

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

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

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

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

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

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"

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) : "";
}

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";
}

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"