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
可以很好的分割字符串,而且语义优雅。