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);
}
}
添加回答
舉報