我正在逐行阅读文本文件,如果它们包含特定列表中存在的单词,我想将每一行拆分。
示例:
String str1 = BuraBua is the Place I live in.
String str2 = New York is the Place I live.
现在我有一个字符串列表,例如:List li = Arrays.asList("BuraBura", "New York");
我想要类似的东西
String[] strList = str1.split(// if str1 contains a word from li then split on that basis);
有任何建议吗?
答案 0 :(得分:0)
这很简单。您可以通过迭代白名单/密钥来做到这一点。
方法:
private final List<String> keys = Arrays.asList("apple", "orange");
public List<String> getSplitted(String text) {
List<String> parts = new ArrayList<>();
keys.forEach(key -> {
if (text.toLowerCase().contains(key.toLowerCase()))
parts.addAll(Arrays.asList(text.split(key)));
});
return parts;
}
方法
private final List<String> keys = Arrays.asList("apple", "orange");
public List<String> getSplitted(String text) {
List<String> parts = new ArrayList<>();
for (String key : keys) {
if (text.toLowerCase().contains(key.toLowerCase()))
parts.addAll(Arrays.asList(text.split(key)));
}
return parts;
}
def "Splitter test"() { given: def text = "I like orange very much. Because orange is very delicious" when: def result = new Splitter().getSplitted(text) then: result == ["I like ", " very much. Because ", " is very delicious"] }
如果您的需求不同,请发表评论。
答案 1 :(得分:-1)
List<List<String>> lo = li.stream()
.filter(str -> str1.contains(str))
.map(str -> { return Arrays.asList(str1.split(str)); })
.collect(Collectors.toList());
注意:如果您的输入包含多个分割字符串,则必须进一步修改。如果碰巧是这种情况,则可以尝试进行循环。希望它能提供一些路径。谢谢