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) 限制拆分出的字符串数量