split和splitPreserveAllTokens

\color{red}{使用split()时应注意检查最后一个分隔符后面有无内容,否则最终分割出的数组元素个数有可能与预期得到的个数不相符,导致异常!}

String str = ",1,2,,";
String[] list1 = str.split(",");
String[] list2 = str.split(",",-1);
String[] list3 = StringUtils.split(str,",");
String[] list4 = StringUtils.splitPreserveAllTokens(str,",");
System.out.println("字符串str:" + str);
System.out.println("str.split(\",\")截取后数组元素个数:" + str.split(",").length);//末尾分隔符全部忽略
for (String str1 : list1) {
    System.out.println("\"" + str1 + "\"");//末尾分隔符全部忽略
System.out.println("str.split(\",\",-1)截取后数组元素个数:" + str.split(",",-1).length);//不忽略任何一个分隔符
for (String str1 : list2) {
    System.out.println("\"" + str1 + "\"");//末尾分隔符全部忽略
System.out.println("StringUtils.split(str,\",\")截取后数组元素个数:" + StringUtils.split(str,",").length);//最前面的和末尾的分隔符全部都忽略,apache commons
for (String str1 : list3) {
    System.out.println("\"" + str1 + "\"");//末尾分隔符全部忽略
System.out.println("StringUtils.splitPreserveAllTokens(str,\",\")截取后数组元素个数:" + StringUtils.splitPreserveAllTokens(str,",").length);//不忽略任何一个分隔符 apache commons
for (String str1 : list4) {
    System.out.println("\"" + str1 + "\"");//末尾分隔符全部忽略
字符串str:,1,2,,
str.split(",")截取后数组元素个数:3
str.split(",",-1)截取后数组元素个数:5
StringUtils.split(str,",")截取后数组元素个数:2
StringUtils.splitPreserveAllTokens(str,",")截取后数组元素个数:5