有一个字符串是分隔字符串: item_1|item_2|item_3
,在本例中分隔符号是 |
。
我的老板不喜欢使用 split
方法来获取字符串的不同部分:他认为这样做有风险,但他不太确定风险是什么。那么还有其他方法可以从分离的字符串中获取List
吗?
最佳答案
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, , ]
关于java - 除了拆分之外,还有其他方法从字符串中获取列表吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54783750/