Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

string

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

like image 674
Mithrax Avatar asked Feb 12 '10 22:02

Mithrax


People also ask

Can strings be multiplied in Java?

We can multiply string in java using appending a particular string in a loop using StringBuffer. append() and it will make sure that string is repeating n time.

Can strings be multiply?

Multiplication. You can do some funny things with multiplication and strings. When you multiply a string by an integer, Python returns a new string. This new string is the original string, repeated X number of times (where X is the value of the integer).

How do you repeat a string?

JavaScript String repeat() The repeat() method returns a string with a number of copies of a string. The repeat() method returns a new string. The repeat() method does not change the original string.


1 Answers

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");     } } 
like image 137
Andi Avatar answered Oct 02 '22 21:10

Andi