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:
" ".repeat(10);
generate(() -> " ").limit(10).collect(joining());
where:
import static java.util.stream.Collectors.joining;
import static java.util.stream.Stream.generate;
The for loop will be optimized by the compiler. In such cases like yours you don't need to care about optimization on your own. Trust the compiler.
BTW, if there is a way to create a string with n space characters, than it's coded the same way like you just did.
int c = 10; String spaces = String.format("%" +c+ "c", ' '); this will solve your problem.
Want String to be of fixed size, so you either pad or truncate, for tabulating data...
class Playground {
private static String fixStrSize(String s, int n) {
return String.format("%-" + n + "s", String.format("%." + n +"s", s));
}
public static void main(String[ ] args) {
System.out.println("|"+fixStrSize("Hell",8)+"|");
System.out.println("|"+fixStrSize("Hells Bells Java Smells",8)+"|");
}
}
|Hell |
|Hells Be|
Excellent reference here.
Considering we have:
String c = "c"; // character to repeat, for empty it would be " ";
int n = 4; // number of times to repeat
String EMPTY_STRING = ""; // empty string (can be put in utility class)
String resultOne = IntStream.range(0,n)
.mapToObj(i->c).collect(Collectors.joining(EMPTY_STRING)); // cccc
String resultTwo = String.join(EMPTY_STRING, Collections.nCopies(n, c)); //cccc
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.