本文介紹了使用 String.format() 打印空格的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我該如何重寫:
for (int i = 0; i < numberOfSpaces; i++) {
System.out.print(" ");
}
使用 String.format()
?
PS
我很確定這是可能的,但是 javadoc 有點混亂.
I'm pretty sure that this is possible but the javadoc is a bit confusing.
推薦答案
需要指定字段的最小寬度.
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");
這會給你 numberOfSpaces-5 個空格,然后是 Hello.如果您希望 Hello 出現在左側,請在 numberOfSpaces 之前添加一個減號.
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.
這篇關于使用 String.format() 打印空格的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!