Common Ways to Build a String We'll iterate through a for loop N times appending the repeated character: StringBuilder builder = new StringBuilder(N); for (int i = 0; i < N; i++) { builder. append("a"); } String newString = builder. toString(); assertEquals(EXPECTED_STRING, newString);
To define String array of specific size in Java, declare a string array and assign a new String array object to it with the size specified in the square brackets. String arrayName[] = new String[size]; //or String[] arrayName = new String[size];
Syntax to declare string of given sizestring s(N, X); The above line of code declares a string of size N filled with character X.
What does \n mean in Java? This means to insert a new line at this specific point in the text. In the below example, "\n" is used inside the print statement, which indicates that the control is passed to the next line. As a result, the text following "\n" will be printed on the next line.
Likely the shortest code using the String
API, exclusively:
String space10 = new String(new char[10]).replace('\0', ' ');
System.out.println("[" + space10 + "]");
// prints "[ ]"
As a method, without directly instantiating char
:
import java.nio.CharBuffer;
/**
* Creates a string of spaces that is 'spaces' spaces long.
*
* @param spaces The number of spaces to add to the string.
*/
public String spaces( int spaces ) {
return CharBuffer.allocate( spaces ).toString().replace( '\0', ' ' );
}
Invoke using:
System.out.printf( "[%s]%n", spaces( 10 ) );
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);
Hmm now that I think about it, maybe Arrays.fill
:
char[] charArray = new char[length];
Arrays.fill(charArray, ' ');
String str = new String(charArray);
Of course, I assume that the fill
method does the same thing as your code, so it will probably perform about the same, but at least this is fewer lines.
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.
" ".repeat(10);
generate(() -> " ").limit(10).collect(joining());
where:
import static java.util.stream.Collectors.joining;
import static java.util.stream.Stream.generate;
In Java 8 you can use String.join
:
String.join("", Collections.nCopies(n, s));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With