Rectangle 27 0

loops How to repeat string "n" times in java?


StringUtils.repeat("Hello"," ",2);

In the above example we are repeating Hello string two times with space as separator. we can give n number of times in 3 argument and any separator in second argument.

The class is actually "StringUtils" not "Stringutils"

This is my preferred solution too as it is very readable, and especially when using a separator it has its special cases taken care of

To repeat string n number of times we have a repeat method in Stringutils class from Apache commons.In repeat method we can give the String and number of times the string should repeat and the separator which separates the repeated strings.

Note
Rectangle 27 0

loops How to repeat string "n" times in java?


str2 = new String(new char[10]).replace("\0", "hello");
Note