天天看點

java字元串格式化處理技巧java字元串格式化處理技巧

java字元串格式化處理技巧

介紹

有時我們可能想要獲得指定格式的字元串資訊,有些資料是根據動态擷取的,
那麼使用String的靜态方法format(String string,Object...args)是一個不錯的選擇。
           

應用場景

本人開發中接觸到的是短信模闆動态填充内容,這算一個小知識點。
           

String format靜态方法

format靜态方法

//Returns a formatted string using the specified format string and arguments.

public static String format(String format, Object... args) {            
        return new Formatter().format(format, args).toString();
    }

public static String format(Locale l, String format, Object... args) {
        return new Formatter(l).format(format, args).toString();
    }
           

格式化參數和使用

常用轉換符       說明
%s              字元串類型
%c              字元類型
%b              布爾類型
%d              整數類型(十進制)
%f              浮點類型
%%              百分比類型
...

其實還有很多比如日期格式化參數,但是我并不推薦掌握那麼多,開發中大多數情況下%s都能滿足的。
最後實在無法達到需求,那麼自己轉換下或再查文檔不遲。
           

使用Code

System.out.println(String.format("hello %s", "world"));//hello world
System.out.println(String.format("hello %c", 'a'));//hello a
System.out.println(String.format("hello %b", false));//hello false
System.out.println(String.format("hello %d", 15));//hello 15
System.out.println(String.format("hello %f", 3.14));//hello 3.140000(注意幫我們算精度了,還是我們自己處理成String類型用%s傳更好)
System.out.println(String.format("合格率 %d%%", 20));//合格率 20%
           

總結

jdk1.5之後,String類中增加兩個format靜态方法幫助我們格式化字元串資料,這也是一個小知識點我們應該掌握。
           

參考

1、http://blog.csdn.net/lonely_fireworks/article/details/7962171