I'd like to create a function that has the following signature:
public String createString(int length, char ch)
It should return a string of repeating characters of the specified length.
For example if length is 5 and ch is 'p' the return value should be:
ppppp
Is there a way to do this without looping until it is the required length?
And without any externally defined constants?
Here is the shortest version (Java 1.5+ required): repeated = new String(new char[n]). replace("\0", s); Where n is the number of times you want to repeat the string and s is the string to repeat.
Java has a repeat function to build copies of a source string: String newString = "a". repeat(N); assertEquals(EXPECTED_STRING, newString);
To define String array of specific size in Java, declare a string array and assign a new String array object to it with the size specified in the square brackets. String arrayName[] = new String[size]; //or String[] arrayName = new String[size];
char[] chars = new char[len]; Arrays.fill(chars, ch); String s = new String(chars);
StringUtils.repeat(str, count)
from apache commons-lang
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