views:

797

answers:

2

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.

+7  A: 

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

Will give you Hello followed by numberOfSpaces-5 at the end. If you want Hello to appear on the right then add a minus sign in before numberOfSpaces.

pjp
in C I would write: printf("%.*s", numberOfSpacs, " "); without any string concatenation
dfa
Or, if you're feeling saucy, String.format(String.format("%%%ds", numberOfSpaces), "")
skaffman
@skaffman: nicely meta :)
Jeremy Smyth
@skaffman: lol :)))
dfa
+1  A: 
int numberOfSpaces = 3;
String space = String.format("%"+ numberOfSpaces +"s", " ");
willcodejavaforfood
I love it when a get a pity upvote for answering too late :)
willcodejavaforfood
You should be thankful for all the upvotes you just got for the int[] array conversion question!
Adamski
@Adamski - Thankful for all upvotes, but I was worried I would only get downvoted because people could not understand his question and the problem with Arrays.asList :)
willcodejavaforfood