print spaces with String.format()

JavaStringFormat

Java Problem Overview


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.

Java Solutions


Solution 1 - Java

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.

Solution 2 - Java

int numberOfSpaces = 3;
String space = String.format("%"+ numberOfSpaces +"s", " ");

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondfaView Question on Stackoverflow
Solution 1 - JavapjpView Answer on Stackoverflow
Solution 2 - JavawillcodejavaforfoodView Answer on Stackoverflow