views:

216

answers:

5

I was wondering what the easiest way is to convert an integer to the equivalent number of blank spaces. I need it for the spaces between nodes when printing a binary search tree. I tried this

  int position = printNode.getPosition(); 
  String formatter = "%1"+position+"s%2$s\n";
  System.out.format(formatter, "", node.element);

But I am getting almost 3 times as many spaces compared to the int value of position. I'm not really sure if I am formatting the string right either. Any suggestions would be great! If it makes it clearer, say position = 6; I want 6 blank spaces printed before my node element.

+3  A: 

Why not loop over the integer and add a space on each iteration?

String spaces = "";
for (int i = 0 ; i < position ; i++) spaces += " ";

And you can use StringBuilder instead of String, if position might get very big and performance is an issue.

Oak
If you are going to do code like this, I would insist (if you where in my team) that you use a StringBuilder. Regardless of how many times you looped, using Strings like this is very inefficient and not recommended because the compiler will internally use StringBuilders to do the work anyway. But instead of doing it once, it will do it every loop. Also check out the Formatter class. It's doco talks about right justifying numbers using the width specification.
Derek Clarkson
+4  A: 

I think you meant something like:

    int n = 6;
    String s = String.format("%1$#"+n+"s", "");

System.out.format("[%13s]%n", "");  // prints "[             ]" (13 spaces)
System.out.format("[%1$3s]%n", ""); // prints "[   ]" (3 spaces)
Eyal Schneider
+1. This answer is the simplest fix to OP's original problem: OP was just missing the `$` character.
polygenelubricants
+5  A: 

You can create a char[] of the desired length, Arrays.fill it with spaces, and then create a String out of it (or just append to your own StringBuilder etc).

import java.util.Arrays;

int n = 6;
char[] spaces = new char[n];
Arrays.fill(spaces, ' ');
System.out.println(new String(spaces) + "!");
// prints "      !"

If you're doing this with a lot of possible values of n, instead of creating and filling new char[n] every time, you can create just one long enough string of spaces and take shorter substring as needed.

polygenelubricants
I think this will be faster than string buffer.
Martijn Courteaux
+3  A: 

Straight foward solution:

int count = 20;

StringBuilder sb = new StringBuilder(count);
for (int i=0; i < count; i++){
 sb.append(" ");
}
String s = sb.toString();

StringBuilder is efficient in terms of speed.

Sylar
I should add "`String spaces = sb.toString();`"
Martijn Courteaux
Right, added it to the code.
Sylar
+1  A: 

This is an easy, but rubbish, way:

 int count = 20;
 String spaces = String.format("%"+count+"s", "");

or filled in

String spaces = String.format("%20s", "");
Martijn Courteaux
Why would this be rubbish?
polygenelubricants