Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: String - add character n-times [duplicate]

Tags:

java

string

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.

like image 210
user905686 Avatar asked Dec 07 '11 11:12

user905686


People also ask

How do you add a character multiple times to a string in Java?

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

How do you repeat a string for n times?

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.

How do you multiply a character 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. Another way is using String.

How do you add all characters to a string in Java?

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.


1 Answers

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.

like image 97
zeller Avatar answered Sep 20 '22 03:09

zeller