在 Java 中左填充字串
要左填充字串,可使用 String.format 並設定空格。
String.format("|%20s|", "demotext")
如果在上面加上 30,它會從開頭起將第一個字串顯示在 30 個空格之後。
String.format("|%30s|", "demotext")
示例
public class Demo { public static void main(String []args) { System.out.print(String.format("|%20s|", "demotext")); System.out.println("Left padded!"); } }
輸出
| demotext|Left padded
廣告