Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

print spaces with String.format()

how I can rewrite this:

for (int i = 0; i < numberOfSpaces; i++) {     System.out.print(" "); } 

using String.format()?

PS

I'm pretty sure that this is possible but the javadoc is a bit confusing.

like image 921
dfa Avatar asked Jul 02 '09 11:07

dfa


People also ask

How do you put a space in a string format?

Use the String. format() method to pad the string with spaces on left and right, and then replace these spaces with the given character using String. replace() method. For left padding, the syntax to use the String.

How do I make 5 spaces in Java?

The simplest way to properly space your output in Java is by adding manual spacing. For instance, to output three different integers, "i," "j" and "k," with a space between each integer, use the following code: System. out.

Can we give space in string?

To add a space between the characters of a string, call the split() method on the string to get an array of characters, and call the join() method on the array to join the substrings with a space separator, e.g. str. split(''). join(' ') . Copied!


2 Answers

int numberOfSpaces = 3; String space = String.format("%"+ numberOfSpaces +"s", " "); 
like image 34
willcodejavaforfood Avatar answered Sep 22 '22 20:09

willcodejavaforfood


You need to specify the minimum width of the field.

String.format("%" + numberOfSpaces + "s", "");  

Why do you want to generate a String of spaces of a certain length.

If you want a column of this length with values then you can do:

String.format("%" + numberOfSpaces + "s", "Hello");  

which gives you numberOfSpaces-5 spaces followed by Hello. If you want Hello to appear on the left then add a minus sign in before numberOfSpaces.

like image 137
pjp Avatar answered Sep 25 '22 20:09

pjp