问题现象:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;public class test06 {public static void main(String[] args) {// Java split()函数 分割空字符串长度为1的解释;String s2 = "";String[] arr2 = s2.split(",");System.out.println("arr2.len:"+arr2.length);}
}
输出:
arr2.len:1
这是为什么?
查看源码:
public String[] split(String regex, int limit) {/* fastpath if the regex is a* (1) one-char String and this character is not one of the* RegEx's meta characters ".$|()[{^?*+\\", or* (2) two-char String and the first char is the backslash and* the second is not the ascii digit or ascii letter.*/char ch = 0;if (((regex.length() == 1 &&".$|()[{^?*+\\".indexOf(ch = regex.charAt(0)) == -1) ||(regex.length() == 2 &®ex.charAt(0) == '\\' &&(((ch = regex.charAt(1))-'0')|('9'-ch)) < 0 &&((ch-'a')|('z'-ch)) < 0 &&((ch-'A')|('Z'-ch)) < 0)) &&(ch < Character.MIN_HIGH_SURROGATE ||ch > Character.MAX_LOW_SURROGATE)){int off = 0;int next = 0;boolean limited = limit > 0;ArrayList<String> list = new ArrayList<>();while ((next = indexOf(ch, off)) != -1) {if (!limited || list.size() < limit - 1) {list.add(substring(off, next));off = next + 1;} else { // last one//assert (list.size() == limit - 1);int last = length();list.add(substring(off, last));off = last;break;}}// If no match was found, return thisif (off == 0)return new String[]{this};// Add remaining segmentif (!limited || list.size() < limit)list.add(substring(off, length()));// Construct resultint resultSize = list.size();if (limit == 0) {while (resultSize > 0 && list.get(resultSize - 1).isEmpty()) {resultSize--;}}String[] result = new String[resultSize];return list.subList(0, resultSize).toArray(result);}return Pattern.compile(regex).split(this, limit);}
发现问题:
问题原因:当正则表达式匹配不到时,实际返回了一个数组,并且数组里面包含了当前的空字符串,所以就导致结果数组长度为1了;
如何规避:
需判空处理:举例如下;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;public class test06 {public static void main(String[] args) {// 三元运算生成空集合和空数组;规避split()函数 分割空字符串长度为1的问题;String str2 = "";//String str2 = "北京,上海,广州";String[] str_arr = str2.isEmpty()? new String[]{}:str2.split(",");System.out.println("str_arr.len:"+str_arr.length);List<String> str_list = str2.isEmpty()? new ArrayList<>():Arrays.asList(str2.split(","));System.out.println("str_list.len:"+str_list.size());}
}
打印输出:
str_arr.len:0
str_list.len:0
问题完美解决!