我正在尝试创建自己的拆分方法,该方法在输出中包含分隔符。到目前为止我有这个代码:
private static String[] split(String string, String regex) throws InterruptedException {
ArrayList<String> output = new ArrayList<String>();
String leftovers = string;
if (regex.charAt(0) != '[' && regex.charAt(regex.length() - 1) != ']') {
int i = 0;
while (!leftovers.isEmpty()) {
if (i == leftovers.indexOf(regex)) {
if (!leftovers.substring(0, leftovers.indexOf(regex)).isEmpty()) {
output.add(leftovers.substring(0, leftovers.indexOf(regex)));
}
output.add(regex);
leftovers = leftovers.substring(i + regex.length());
i = 0;
} else if (leftovers.indexOf(regex) == -1) {
output.add(leftovers);
leftovers = "";
} else {
i++;
}
}
} else {
char[] regexChars = new char[regex.length() - 2];
for (int i = 0; i < regexChars.length; i++) {
regexChars[i] = regex.charAt(i + 1);
}
int i = 0;
for (int j = 0; j < regexChars.length; j++) {
while (!leftovers.isEmpty()) {
if (i == leftovers.indexOf(regexChars[j])) {
if (!leftovers.substring(0, leftovers.indexOf(regexChars[j])).isEmpty()) {
output.add(leftovers.substring(0, leftovers.indexOf(regexChars[j])));
}
output.add(Character.toString(regexChars[j]));
leftovers = leftovers.substring(i + 1);
i = 0;
} else if (leftovers.indexOf(regexChars[j]) == -1) {
output.add(leftovers);
leftovers = "";
} else {
i++;
}
}
}
}
return output.toArray(new String[0]);
}
我试图传入的输入参数是“a?b?gf#e”和“[?#]”。但是,我得到的输出是[a, ?, b, ?, gf, null, e]
. 如果我将正则表达式中的分隔符反转为“[#?]”,我会得到[a, a?b?gf#e]
谁能告诉我我做错了什么?仅供参考,我不想使用 Pattern 和 Matcher 类,我们根本不允许使用内置的 split 方法。