61

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?

Mike
  • 14,010
  • 29
  • 101
  • 161
Ron Tuffin
  • 53,859
  • 24
  • 66
  • 78

5 Answers5

109
char[] chars = new char[len];
Arrays.fill(chars, ch);
String s = new String(chars);
Mike
  • 14,010
  • 29
  • 101
  • 161
Joel Shemtov
  • 3,008
  • 2
  • 22
  • 22
40

StringUtils.repeat(str, count) from apache commons-lang

Eugene Evdokimov
  • 2,220
  • 2
  • 28
  • 33
Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
30

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"
Mike
  • 14,010
  • 29
  • 101
  • 161
  • 3
    Seeing all the solutions, I wonder whether `String` should have a constructor like `String(int size, char filler)` or a method `fillWith(char filler)`. – U. Windl May 11 '18 at 10:34
8

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.

T.Gounelle
  • 5,953
  • 1
  • 22
  • 32
1

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;    
    }
Sohan
  • 6,252
  • 5
  • 35
  • 56