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:
You can replace StringBuffer
with StringBuilder
( the latter is not synchronized, may be a faster in a single thread app )
And you can create the StringBuilder
instance once, instead of creating it each time you need it.
Something like this:
class BuildString {
private final StringBuilder builder = new StringBuilder();
public String stringOf( char c , int times ) {
for( int i = 0 ; i < times ; i++ ) {
builder.append( c );
}
String result = builder.toString();
builder.delete( 0 , builder.length() -1 );
return result;
}
}
And use it like this:
BuildString createA = new BuildString();
String empty = createA.stringOf( ' ', 10 );
If you hold your createA
as a instance variable, you may save time creating instances.
This is not thread safe, if you have multi threads, each thread should have its own copy.