Create a string with n characters

C. Ross picture C. Ross · May 10, 2010 · Viewed 200.7k times · Source

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:

StringBuffer outputBuffer = new StringBuffer(length);
for (int i = 0; i < length; i++){
   outputBuffer.append(" ");
}
return outputBuffer.toString();

Is there a better way to accomplish the same thing. In particular I'd like something that is fast (in terms of execution).

Answer

polygenelubricants picture polygenelubricants · May 11, 2010

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 ) );