1. 程式人生 > >Guava字串處理Joiner、Splitter

Guava字串處理Joiner、Splitter

1、連線Joiner
用分隔符連線字串時,如果字串中途含有null,操作起來會需要特殊處理,Guava中提供的Joiner讓字串連線更簡潔。

//連結字串並忽略null,否則存在null報空指標異常
Joiner joiner = Joiner.on("|").skipNulls();
String result = joiner.join("one", null, "two", "three");
結果:one|two|three

//useForNull(String)方法可以給定某個字串來替換null,而不像skipNulls()方法是直接忽略null。
Joiner joiner = Joiner.
on("|").useForNull("12345"); String result = joiner.join("one", null, "two", "three"); 結果:one|12345|two|three //Joiner也可以用來連線物件型別,它會把物件的toString()的值連線起來。 List list = Arrays.asList("one", "two", "three"); 結果:one|two|three

2、拆分Splitter

//String.split方法會自動省略最後一個字串
String data = ",1,2,,3,";
String[] array
=data.split(","); 結果為:"","1","2","","3" Splitter splitter = Splitter.on(","); Iterable<String> iterable = splitter.split(data); 結果為:"","1","2","","3",""

其它常用方法:
omitEmptyStrings() 從結果中自動忽略空字串
trimResults() 移除結果字串的前導空白和尾部空白
trimResults(CharMatcher) 給定匹配器,移除結果字串的匹配字元
limit(int) 限制拆分出的字串數量