63

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?

1
  • 2
    It does look like a duplicate question, but the answers here are much nicer :) Commented Dec 5, 2013 at 15:31

5 Answers 5

110
char[] chars = new char[len];
Arrays.fill(chars, ch);
String s = new String(chars);
Sign up to request clarification or add additional context in comments.

1 Comment

Really simple and helpful.
41

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

4 Comments

Perfect! Why write three lines when you can write 1?
@deGoot, cause you need third-party library for that
which you probably already have.. :)
@Bozho not rly.....
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"

1 Comment

Seeing all the solutions, I wonder whether String should have a constructor like String(int size, char filler) or a method fillWith(char filler).
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.

2 Comments

Upvoted for coolness.
To avoid generating and discarding the IntStream values String p10Times = Stream.generate(() -> "p").limit(10).collect(Collectors.joining());
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;    
    }

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.