handle empty strings properly in Pattern.split

We were incorrectly returning an empty array when the input was empty,
whereas we ought to return an array containing a single empty string.
When the pattern to match was empty, we went into a loop to create an
infinite list of empty strings, only to crash once we've run out of
memory.  This commit addresses both problems.
This commit is contained in:
Joel Dice
2010-09-06 11:16:27 -06:00
parent a26eb1b2b9
commit 250a77dc13
2 changed files with 59 additions and 5 deletions

View File

@ -115,23 +115,34 @@ public class Pattern {
List<CharSequence> list = new LinkedList();
int index = 0;
int trailing = 0;
while (index < input.length() && list.size() < limit) {
int i = indexOf(input, pattern, index);
int patternLength = pattern.length();
while (index < input.length() && list.size() < limit - 1) {
int i;
if (patternLength == 0) {
if (list.size() == 0) {
i = 0;
} else {
i = index + 1;
}
} else {
i = indexOf(input, pattern, index);
}
if (i >= 0) {
if (i == index) {
if (patternLength != 0 && i == index) {
++ trailing;
} else {
trailing = 0;
}
list.add(input.subSequence(index, i));
index = i + pattern.length();
index = i + patternLength;
} else {
break;
}
}
if (strip && index == input.length()) {
if (strip && index > 0 && index == input.length()) {
++ trailing;
} else {
trailing = 0;