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".
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.
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).
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.
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"); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With