Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert integer to equivalent number of blank spaces

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.

like image 602
mike Avatar asked Apr 14 '10 05:04

mike


2 Answers

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)
like image 78
Eyal Schneider Avatar answered Sep 21 '22 20:09

Eyal Schneider


This is an easy, but rubbish, way:

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

or filled in

String spaces = String.format("%20s", "");
like image 22
Martijn Courteaux Avatar answered Sep 19 '22 20:09

Martijn Courteaux