java占位符

自己在这里总结了三种占位符形式:看下面代码即可

[java]  view plain  copy
  1. String stringFormat  = "lexical error at position %s, encountered %s, expected %s ";   
  2.   
  3. String messageFormat ="lexical error at position {0}, encountered {1}, expected {2}";  
  4.   
  5. System.out.println(String.format(stringFormat, 123100456));  
  6.   
  7. System.out.println(MessageFormat.format(messageFormat, new Date(), 100456));  

以上是两种常见的使用形式,这里还有另一种:

[java]  view plain  copy
  1. %n$ms:代表输出的是字符串,n代表是第几个参数,设置m的值可以在输出之前放置空格   
  2.   
  3.   
  4. %n$md:代表输出的是整数,n代表是第几个参数,设置m的值可以在输出之前放置空格,也可以设为0m,在输出之前放置m个0   
  5.   
  6.   
  7. %n$mf:代表输出的是浮点数,n代表是第几个参数,设置m的值可以控制小数位数,如m=2.2时,输出格式为00.00  

[html]  view plain  copy
  1. 使用举例:  
  2.   
  3. String format = "%1$-25s%2$-48s";  
  4.   
  5. System.out.format(format, "111","222");  

猜你喜欢

转载自blog.csdn.net/g1998i/article/details/79649055