Java String.split 和 StringUtils.split

Java代码 复制代码
  1. String[] strs = "".split(",");  
String[] strs = "".split(",");


结果是strs.length=1,strs[0]=""

Java代码 复制代码
  1. String[] strs = ",".split(",");  
String[] strs = ",".split(",");


结果是strs.length=0

Java代码 复制代码
  1. String[] strs = ",1,".split(",");  
String[] strs = ",1,".split(",");


结果是strs.length=2,strs[0]="",strs[1]="1"

String.split使用起来潜规则比较多,即使自己清楚,别人也未必一眼就看明白。为了不引起误会,建议使用StringUtils.split来替代,它对空字符串""会进行过滤。

Java代码 复制代码
  1. String[] strs = StringUtils.split(",1,,2,"",");  
String[] strs = StringUtils.split(",1,,2,", ",");


结果是strs.length=2,strs[0]="1",strs[1]="2"

你可能感兴趣的:(java)