Is there a way in java to create a string with a specified number of a specified character? In my case, I would need to create a string with 10 spaces. My current code is:
Just replace your StringBuffer with a StringBuilder. Hard to beat that.
If your length is a big number, you might implement some more efficient (but more clumsy) self-appendding, duplicating the length in each iteration:
public static String dummyString(char c, int len) {
if( len < 1 ) return "";
StringBuilder sb = new StringBuilder(len).append(c);
int remnant = len - sb.length();
while(remnant > 0) {
if( remnant >= sb.length() ) sb.append(sb);
else sb.append(sb.subSequence(0, remnant));
remnant = len - sb.length();
}
return sb.toString();
}
Also, you might try the Arrays.fill()
aproach (FrustratedWithFormsDesigner's answer).