tags:

views:

184

answers:

9

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

+1  A: 

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. :)

Edit: 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.

kalkin
even if this was not optimised - how often is this created in your program - if often save in a static variable or other cache
Mark
btw Array.fill() just loops through the array./me need definitively more points to comment on others posts :)
kalkin
@Mark Length is variable, so it seems silly to save it. What would I do, have a `static Dictionary<int, String>`?
C. Ross
No just a string
Mark
A: 

I know of no built-in method for what you're asking about. However, for a small fixed length like 10, your method should be plenty fast.

Lord Torgamus
If only it was a small fixed length like 10.
C. Ross
+1  A: 

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.

NOTE: this code may not actually compile as-written (I haven't actually tried this).

FrustratedWithFormsDesigner
After checking the source, it seems that this does in fact do exactly what the OP posted: line 806 of http://www.docjar.com/html/api/java/util/Arrays.java.html
Lord Torgamus
@Lord Torgamus: Yes, but it looks neater. ;)
FrustratedWithFormsDesigner
@Frustrated: quite so.
Lord Torgamus
@Lord Torgamus Was the OP's question edited? Because in the version I see, he's looping on StringBuffer.append(), and Frustrated's version is doing a fill (which of course loops doing char assignments to the array). Not the same thing at all.
CPerkins
@CPerkins, fair enough, I wasn't clear. My point is that both of them do a character-by-character insertion inside of a for loop.
Lord Torgamus
@Lord Torgamus - Agreed on that. pity the jvm can't just do a memset. Price we pay for wide characters.
CPerkins
A: 

How about this?

StringBuilder sb = new StringBuilder(10); // creates empty builder, capacity 10
return sb.append("          ");  // adds 10 space characters
Jivings
This isn't dynamic; the OP might have to deal with different lengths in the future.
Lord Torgamus
I think he needs variable length strings. 10 was just an example (poorly worded though).
FrustratedWithFormsDesigner
Indeed, if you were going for a non-dynamic solution, you could dispense with the `StringBuilder` altogether and just hardcode that ten-space string in.
Lord Torgamus
Nothing in the question about the function needing to be dynamic.
Jivings
@Jivings, the OP asked the question both in general (first sentence) and for a specific case. And even if he did only need the specific case, this is inefficient.
Lord Torgamus
@Lord Torgamus, fair enough. My answer is a bit daft :)
Jivings
A: 

Just replace your StringBuffer with a StringBuilder. Hard to beat that.

If your length is a big number, you might implement some more efficient (but more clumsy) self-appendding, duplicating the length in each iteration:

 public static String dummyString(char c, int len) {
  if( len < 1 ) return "";
  StringBuilder sb = new StringBuilder(len).append(c);
  int remnant = len - sb.length();
  while(remnant  > 0) {
   if( remnant  >= sb.length() ) sb.append(sb);
   else sb.append(sb.subSequence(0, remnant));
   remnant  = len - sb.length();
  }
  return sb.toString();
 }

Also, you might try the Arrays.fill() aproach (FrustratedWithFormsDesigner's answer).

leonbloy
Can you name some of the variables more than one character?
C. Ross
A: 

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.

OscarRyz
I think you mean that the *latter* is not synchronized.
Syntactic
yeap, that's what I meant, corrected!
OscarRyz
A: 

In most cases you only need Strings upto a certains length, say 100 spaces. You could prepare an array of Strings where the index number is equal to the size of the space-filled string and lookup the string, if the required length is within the limits or create it on demand if it's outside the boundary.

Andreas_D
A: 

How about this?

char[] bytes = new char[length];
Arrays.fill(bytes, ' ');
String str = new String(bytes);
Martijn Courteaux
+2  A: 

This one-liner is probably the shortest you can do it using only String API:

    String space10 = new String(new char[10]).replace('\0', ' ');

    System.out.println("[" + space10 + "]");
    // prints "[          ]"
polygenelubricants
+1, an alternative to `new String(char[])` is btw `CharBuffer.allocate(10).toString()`.
BalusC