import java.util.Arrays;
import java.util.regex.Pattern;
public class StringSplit {
public static void main(String[] args) {
String str = "ABC";
// 测试String#split()方法
String[] elems = str.split("");
System.out.println(Arrays.toString(elems));
// 结果:
// Java 7 -> [, A, B, C]
// Java 8 -> [A, B, C]
// 测试Pattern#split()方法
Pattern delimiter = Pattern.compile("");
elems = delimiter.split(str);
System.out.println(Arrays.toString(elems));
}
}
查了一下,发现java.util.regex.Pattern#String[] split(CharSequence input, int limit)方法中,增加了下面的处理。
// Add segments before each match found
while(m.find()) {
if (!matchLimited || matchList.size() < limit - 1) {
if (index == 0 && index == m.start() && m.start() == m.end()) {
// no empty leading substring included for zero-width match
// at the beginning of the input char sequence.
continue;
}
String match = input.subSequence(index, m.start()).toString();
matchList.add(match);
index = m.end();
} else if (matchList.size() == limit - 1) { // last one
String match = input.subSequence(index,
input.length()).toString();
matchList.add(match);
index = m.end();
}
}