print spaces with String.format()

前端 未结 2 750
日久生厌
日久生厌 2020-12-13 17:10

how I can rewrite this:

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

using String.format()?

相关标签:
2条回答
  • 2020-12-13 17:42

    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.

    0 讨论(0)
  • 2020-12-13 17:53
    int numberOfSpaces = 3;
    String space = String.format("%"+ numberOfSpaces +"s", " ");
    
    0 讨论(0)
提交回复
热议问题