Java generating a Blanks String
is there a more efficient way to generate a String full of blanks with a customizable size like the following:
private String getBlanks (int numberOfBlanks)
{
String theBlanks = "";
for (int i = 0; i < numberOfBlanks; i++)
{
theBlanks = theBlanks + " ";
}
return theBlanks;
}
Perhaps with a StringBuilder
or any other type?
EDIT: Since we have Appache Commons Lang the most convinient way of doing is through the use of String Utils - leftPad, thanks 开发者_Python百科everyone for the answers!
Thanks
Maybe like this:
private String getBlanks(int numberOfBlanks) {
char[] chars = new char[numberOfBlanks];
Arrays.fill(chars, (char)32);
return new String(chars);
}
With Guava
String blanks = Strings.repeat(" ", numOfblanks);
Quick hack using StringUtils:
return StringUtils.leftPad("", numberOfBlanks, ' ');
First of all - use a StringBuilder
, and then return StringBuilder.toString
You want a StringBuilder:
private String getBlanks (int numberOfBlanks)
{
StringBuilder theBlanks = new StringBuilder(numberOfBlanks);
for (int i = 0; i < numberOfBlanks; i++) theBlanks.append(" ");
return theBlanks.toString();
}
String getBlankString(int length){
StringBuffer sb=new StringBuffer(length);
for(int i=0;i<length;i++){
sb.append(" ");
}
return sb.toString();
}
private String getBlanks (int numberOfBlanks) {
StringBuilder sb = new StringBuilder();
sb.setLength(numberOfBlanks);
sb.replace(0, numberOfBlanks-1, " ");
return sb.toString();
}
精彩评论