Likely the shortest code using the String
API, exclusively:
String space10 = new String(new char[10]).replace('', ' ');
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( '', ' ' );
}
Invoke using:
System.out.printf( "[%s]%n", spaces( 10 ) );
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…