views:

180

answers:

3

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?

+8  A: 
char[] chars = new char[len];
Arrays.fill(chars, ch);
String s = new String(chars);
Joel
+5  A: 

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

Bozho
+5  A: 

You can use Arrays#fill() for this.

public String createString(int length, char ch) {
    char[] chars = new char[length];
    Arrays.fill(chars, ch);
    return new String(chars);
}
BalusC
So the fastest, the least-informative and the worst formatted reply counts here? Impressive. I'll try to put less effort in posting answers the next time :/
BalusC
At least it GOT formatted at a point ;) Though, it is impressive. But people seeing an answer with more votes tend to vote for it, somehow.
Bozho
I accepted the answer I did because it was the first correct answer. Thanks @Bozho (cool name btw) for the formating edit.
Ron Tuffin
I wouldn't change anything if I was you. With this wealth of reputation, clearly you do something right.
Joel