先来看几行简单的Java代码,如下:
System.out.println("1,2".split(",").length);
System.out.println("1,2,".split(",").length);
System.out.println("".split(",").length);
System.out.println(",".split(",").length);
接下来,猜一下各行的输出结果。OK,下面给出真正的运行结果:
2
2
1
0
这里先给出jdk相关源码,再来对应分析各自的输出:
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.value.length == 1 &&
".$|()[{^?*+\\".in