3 回答

TA贡献1752条经验 获得超4个赞
import java.util.ArrayList;
import java.util.List;
public class SplitUsingAnotherMethodBecauseBossLikesWastingEveryonesTime {
public static void main(String[] args) {
System.out.println(split("Why would anyone want to write their own String split function in Java?", ' '));
System.out.println(split("The|Split|Method|Is|Way|More|Flexible||", '|'));
}
private static List<String> split(String input, char delimiter) {
List<String> result = new ArrayList<>();
int idx = 0;
int next;
do {
next = input.indexOf(delimiter, idx);
if (next > -1) {
result.add(input.substring(idx, next));
idx = next + 1;
}
} while(next > -1);
result.add(input.substring(idx));
return result;
}
}
输出...
[Why, would, anyone, want, to, write, their, own, String, split, function, in, Java?]
[The, Split, Method, Is, Way, More, Flexible, , ]

TA贡献1799条经验 获得超8个赞
您可以只遍历char字符串中的所有 s,然后用于substring()选择不同的子字符串:
public static List<String> split(String input, char delimiter) {
List<String> output = new LinkedList<>();
int lastIndex = 0;
boolean doubleQuote = false;
boolean singleQuoteFound = false;
for (int i = 0, current, last = 0, length = input.length(); i < length; i++) {
current = input.charAt(i);
if (last != '\\') {
if (current == '"') {
doubleQuote = !doubleQuote;
} else if (current == '\'') {
singleQuoteFound = !singleQuoteFound;
} else if (current == delimiter && !doubleQuote && !singleQuoteFound) {
output.add(input.substring(lastIndex, i));
lastIndex = i + 1;
}
}
last = current;
}
output.add(input.substring(lastIndex));
return output;
}
这是一种非常粗略的方法,但从我的测试来看,它应该处理转义分隔符、单引号'和/或双"引号中的分隔符。
可以这样调用:
List<String> splitted = split("Hello|World|"No|split|here"|\|Was escaped|'Some|test'", '|');
印刷:
[Hello, World, "No|split|here", \|Was escaped, 'Some|test']

TA贡献1786条经验 获得超13个赞
当我们使用拆分字符串时,它会在内部创建 Patterns 对象,该对象会产生开销,但这仅适用于 Java 7 之前的版本,在 Java 7/8 中,它使用自 java 7 以来的索引,它不会有任何正则表达式引擎的开销。但是,如果您确实传递了一个更复杂的表达式,它会恢复为编译一个新模式,这里的行为应该与 Java 6 上的行为相同,您可以使用预编译模式并拆分字符串。
public class MyClass {
static Pattern pattern = Pattern.compile("\\|");
public static void main(String[] args) {
String str = "item_1|item_2|item_3";
Stream<String> streamsName = pattern.splitAsStream(str);
streamsName.forEach(System.out::println);
}
}
添加回答
举报