天天看點

java string常用的占位符形式 

http://www.verydemo.com/map.html

自己在這裡總結了三種占位符形式:看下面代碼即可

String stringFormat  = "lexical error at position %s, encountered %s, expected %s "; 

String messageFormat ="lexical error at position {0}, encountered {1}, expected {2}";

System.out.println(String.format(stringFormat, 123, 100, 456));

System.out.println(MessageFormat.format(messageFormat, new Date(), 100, 456));

以上是兩種常見的使用形式,這裡還有另一種:

%n$ms:代表輸出的是字元串,n代表是第幾個參數,設定m的值可以在輸出之前放置空格 

%n$md:代表輸出的是整數,n代表是第幾個參數,設定m的值可以在輸出之前放置空格,也可以設為0m,在輸出之前放置m個0 

%n$mf:代表輸出的是浮點數,n代表是第幾個參數,設定m的值可以控制小數位數,如m=2.2時,輸出格式為00.00

使用舉例:

String format = "%1$-25s%2$-48s";

System.out.format(format, "111","222");