Can one initialize a Java string with a single repeated character to a specific length
JavaStringInitializationJava Problem Overview
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?
Java Solutions
Solution 1 - Java
char[] chars = new char[len];
Arrays.fill(chars, ch);
String s = new String(chars);
Solution 2 - Java
StringUtils.repeat(str, count)
from apache commons-lang
Solution 3 - Java
Here is an elegant, pure Java, one-line solution:
Java 11+:
String str = "p".repeat(5); // "ppppp"
prior Java 11:
String str = new String(new char[5]).replace("\0", "p"); // "ppppp"
Solution 4 - Java
For the record, with Java8 you can do that with streams:
String p10times = IntStream.range(0, 10)
.mapToObj(x -> "p")
.collect(Collectors.joining());
But this seems somewhat overkill.
Solution 5 - Java
Bit more advance and readable ,
public static String repeat(int len, String ch) {
String s = IntStream.generate(() -> 1).limit(len).mapToObj(x -> ch).collect(Collectors.joining());
System.out.println("s " + s);
return s;
}