6

If i want a String s which would consist of n instances of character A, can this be done cleaner in Java other then

public static String stringOfSize(int size, char ch) {
    StringBuilder s = new StringBuilder();
    while (size-- > 0) {
        s.append(ch);
    }
    return s.toString();
}

Can we do better? Just wondering.

James Raitsev
  • 92,517
  • 154
  • 335
  • 470

2 Answers2

18

Nothing wrong with this code at all... But maybe you can use Arrays.fill():

public static String stringOfSize(int size, char ch)
{
    final char[] array = new char[size];
    Arrays.fill(array, ch);
    return new String(array);
}
fge
  • 119,121
  • 33
  • 254
  • 329
  • I think that this option is the best. To increase speed (but consume more memory) we can also add caching to this solution. Store results in `Map> cache` and then just get right string without generation. – Grzegorz Gajos May 28 '13 at 20:06
7

You could do the following:

return StringUtils.repeat(ch, size);

Note: StringUtils is not built-in to the JDK - see http://commons.apache.org/proper/commons-lang/

Justin Bicknell
  • 4,804
  • 18
  • 26