package javaapplication1;
public class JavaApplication1 {
/**
* Repeat string <b>str</b> <b>times</b> time.
* @param str string to repeat
* @param times repeat str times time
* @return generated string
*/
public static String repeat(String str, int times) {
return new String(new char[times]).replace("\0", str);
}
public static void main(String[] args) {
System.out.println(repeat("*", 5));
}
}
Created
April 16, 2014 11:49
-
-
Save umidjons/10859940 to your computer and use it in GitHub Desktop.
Repeat string N times without loop in Java
If you've Apache 'commons-lang3' already in classpath, org.apache.commons.lang3.StringUtils.repeat(...)
methods use similar technique.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Primitive types (char[], in this case) are instantiated with nulls "number of times", then a String is created from the char[], and the nulls are replaced() with the character you want in str