您的位置:首页 > 编程语言 > Go语言

Google Guava Splitter

2017-03-28 01:20 405 查看
String.split的特殊情况

String[] split = ",a,,b,".split(",");
for (String s : split) {
System.out.println(s);
}
System.out.println(split.length);


输出结果为:

a

b
4

String.split 自动忽略了末尾的空白内容。

不管b后面多少个逗号,返回的数组长度都是4。

改用Guava的Spliter来进行分割

public class TestSplit {

public static void main(String[] args) {
String data = "hello=1&world=2&k=11";
CaseInsensitiveMap map = new CaseInsensitiveMap(
Splitter.on("&").trimResults().withKeyValueSeparator(Splitter.on("=").trimResults().limit(2))
.split(data));
Set<Map.Entry<String, String>> set = map.entrySet();
set.forEach(o -> System.out.println(((Map.Entry) o).getKey() + " , " + ((Map.Entry) o).getValue()));
System.out.println("-------------------------------");
Iterable<String> split = Splitter.on("=").omitEmptyStrings().trimResults().split("1=   2,==2=3,=,3=4");
for (String s : split) {
System.out.println(s);
}
}
}


输出结果为:

k , 11
hello , 1
world , 2
-------------------------------
1
2,
2
3,
,3
4


可以很好的分割字符串,而且语义优雅。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: