Can one initialize a Java string with a single repeated character to a specific length

JavaStringInitialization

Java 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;    
    }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRon TuffinView Question on Stackoverflow
Solution 1 - JavaJoel ShemtovView Answer on Stackoverflow
Solution 2 - JavaBozhoView Answer on Stackoverflow
Solution 3 - JavaMikeView Answer on Stackoverflow
Solution 4 - JavaT.GounelleView Answer on Stackoverflow
Solution 5 - JavaSohanView Answer on Stackoverflow