split(",")与split(",",-1)的区别
下面通过两种情况说明二者的区别
第一种:字符串最后一位是要切割符
代码:
package com.yyy.test;
public class testSplit {
public static void main(String[] args) {
String aaa="a,b,c,d,,,,,,";
String[] split = aaa.split(",");
System.out.println(split.length);
for(String item:split){
System.out.println(item+"==========");
}
System.out.println("1111111111111111111111111111111111111111111111111");
String[] split1 = aaa.split(",", -1);
System.out.println(split1.length);
for (String item:split1){
System.out.println(item+"==========");
}
}
}
执行结果
4
a==========
b==========
c==========
d==========
1111111111111111111111111111111111111111111111111
10
a==========
b==========
c==========
d==========
==========
==========
==========
==========
==========
==========
Process finished with exit code 0
总结:
第一种情况,二者的区别为,如果最后n位都为切割符则split(",")不会继续切割,而split(",",会继续切割)
第二种情况 字符串最后一位不为切割符
代码
package com.yyy.test;
public class testSplit2 {
public static void main(String[] args) {
String aaa="a,b,c,d,,,,,,e";
String[] split = aaa.split(",");
System.out.println(split.length);
for(String item:split){
System.out.println(item+"==========");
}
System.out.println("1111111111111111111111111111111111111111111111111");
String[] split1 = aaa.split(",", -1);
System.out.println(split1.length);
for (String item:split1){
System.out.println(item+"==========");
}
}
}
执行结果
4
a==========
b==========
c==========
d==========
1111111111111111111111111111111111111111111111111
10
a==========
b==========
c==========
d==========
==========
==========
==========
==========
==========
==========
Process finished with exit code 0
总结
第二种情况二者没有区别