Is there a simple way to add a character or another String n-times to an existing String? I couldn’t find anything in String
, Stringbuilder
, etc.
We'll iterate through a for loop N times appending the repeated character: StringBuilder builder = new StringBuilder(N); for (int i = 0; i < N; i++) { builder. append("a"); } String newString = builder. toString(); assertEquals(EXPECTED_STRING, newString);
String Class repeat() Method in Java with Examples The string can be repeated N number of times, and we can generate a new string that has repetitions. repeat() method is used to return String whose value is the concatenation of given String repeated count times.
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. Another way is using String.
insert(int position, double x); str. insert(int position, long x); str. insert(int position, int x); position is the index in string where we need to insert. Return type: A reference to this object.
Apache commons-lang3
has StringUtils.repeat(String, int)
, with this one you can do (for simplicity, not with StringBuilder
):
String original; original = original + StringUtils.repeat("x", n);
Since it is open source, you can read how it is written. There is a minor optimalization for small n-s if I remember correctly, but most of the time it uses StringBuilder
.
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