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:
This worked out for me without using any external libraries in Java 8
String sampleText = "test"
int n = 3;
String output = String.join("", Collections.nCopies(n, sampleText));
System.out.println(output);
And the output is
testtesttest
For good performance, combine answers from aznilamir and from FrustratedWithFormsDesigner
private static final String BLANKS = " ";
private static String getBlankLine( int length )
{
if( length <= BLANKS.length() )
{
return BLANKS.substring( 0, length );
}
else
{
char[] array = new char[ length ];
Arrays.fill( array, ' ' );
return new String( array );
}
}
Adjust size of BLANKS
depending on your requirements. My specific BLANKS
string is about 200 characters length.
A simple method like below can also be used
public static String padString(String str, int leng,char chr) {
for (int i = str.length(); i <= leng; i++)
str += chr;
return str;
}
I highly suggest not to write the loop by hand. You will do that over and over again during the course of your programming career. People reading your code - that includes you - always have to invest time, even if it are just some seconds, to digest the meaning of the loop.
Instead reuse one of the available libraries providing code that does just that like StringUtils.repeat
from Apache Commons Lang:
StringUtils.repeat(' ', length);
That way you also do not have to bother about performance, thus all the gory details of StringBuilder
, Compiler optimisations etc. are hidden.
If the function would turn out as slow it would be a bug of the library.
With Java 11 it becomes even easier:
" ".repeat(length);
Since Java 11 you can simply use String.repeat(count) to solve your problem.
Returns a string whose value is the concatenation of this string repeated
count
times.If this string is empty or
count
is zero then the empty string is returned.
So instead of a loop your code would just look like this:
" ".repeat(length);
How about this?
char[] bytes = new char[length];
Arrays.fill(bytes, ' ');
String str = new String(bytes);