54

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.

1
  • I dont think questions get the credit they deserve so upvoting! Commented Jul 2, 2009 at 11:48

2 Answers 2

74

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.

Sign up to request clarification or add additional context in comments.

3 Comments

in C I would write: printf("%.*s", numberOfSpacs, " "); without any string concatenation
Or, if you're feeling saucy, String.format(String.format("%%%ds", numberOfSpaces), "")
I know this is totally old but: is this possible for leading AND trailing spaces? I knwo that you use the "-" sign for trailing but I don't know if it's possible to combine them
18
int numberOfSpaces = 3;
String space = String.format("%"+ numberOfSpaces +"s", " ");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.