split(String regex)为java.lang.String类的方法,其功能可简单描述为在给定正则表达式的匹配位置拆分该字符串。
该方法的具体定义为
public String[] split(String regex) {
return split(regex, 0);
}
可以很明显地看到方法内部调用了一个重载的split(regex,0)方法,split(regex)方法最终返回一个字符串数组。
split(regex,0)的原型为split(String regex, int limit),该方法中的regex为匹配样板,而参数limit似乎不太好理解,通过查阅api文档得到如下说明
The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array. If the limit n is greater than zero then the pattern will be applied at most n - 1 times, the array’s length will be no greater than n, and the array’s last entry will contain all input beyond the last matched delimiter. If n is non-positive then the pattern will be applied as many times as possible and the array can have any length. If n is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.
翻译如下:
limit这个参数控制样板(pattern)应用的次数,因此它影响结果数组的长度。如果limit的值为n>0,那么样板会被应用n-1次,如此一来结果数组的长度就会不大于n,并且结果数组的最后一个元素会包含从最后一个样板匹配位置的下一个字符到整个输入字符串结束的所有字符。如果n<=0,样板会被尽可能地匹配,所以此时结果数组的长度是未知的;如果此时n=0,那么输入字符串末尾的空格会被丢弃。
上面这段话什么意思?看了说明之后依旧无法理解,下面我们通过实验来探索。
public class Test {
public static void main(String[] args) {
String s1 = "a,b,c";
String s2 = "a,b,c,,,";
String s3 = "a,b,c,,,d";
String[] _s1 = s1.split(",");
String[] _s2 = s2.split(",");
String[] _s3 = s3.split(",");
System.out.print("s1调用split方法后的结果为:");
for (String s : _s1) {
System.out.print("\"" + s + "\"" + "\t");
}
System.out.println();
System.out.print("s2调用split方法后的结果为:");
for (String s : _s2) {
System.out.print("\"" + s + "\"" + "\t");
}
System.out.println();
System.out.print("s3调用split方法后的结果为:");
for (String s : _s3) {
System.out.print("\"" + s + "\"" + "\t");
}
}
}
上面这段代码中使用了只有一个参数的split()方法,该方法调用split(regex,0)方法。调试结果如下

图1
如果将代码中的split(",")方法替换为split("," -1)则得到如下输出
图2
比较s2的输出,可知“如果n<=0,样板会被尽可能地匹配,所以此时结果数组的长度是未知的;如果此时n=0,那么输入字符串末尾的空格会被丢弃。”的涵义,图1中s2的结果不包含靠后的空格,与n=0的情形相匹配;图2中s2的结果包含靠后的所有空格,与n<0相匹配。
如果将代码中的split(",")方法替换为split("," 3)则得到如下输出

图3
从图3可知,从字符“c”开始其后的字符被处理为一个字符串,“,”一共被匹配了(3-1)次,这和当n>0时的情形相符。
理解完文档中的内容后还需要注意如果字符中出现两个相连的样板,则匹配完成后,这两个相连样板会被消去,但他们中间会产生一个空格字符串,该空格字符串会被返回到字符数组String[]中;如果样板出现在字符末尾,那字符串数组String[]中的最后一位元素也是空格
本文详细探讨了Java中String类的split()方法,解释了如何在给定正则表达式的基础上拆分字符串。内容包括split方法的重载形式,limit参数的作用,以及不同limit值对结果数组的影响。通过实例演示了limit为0、负数和正数时的匹配行为,揭示了在连续样板和结尾样板情况下的处理方式。
1万+

被折叠的 条评论
为什么被折叠?



