有诸如“is”、“is not”、“不包含”之类的单词组合。我们必须将这些单词匹配到一个句子中,并且必须将其拆分。
输入:如果姓名是 tom 并且年龄不是 45 岁或姓名不包含 tom,请告诉我。
预期输出:
If name is
tom and age is not
45 or name does not contain
tom then let me know
我尝试了下面的代码来分割和提取,但是“is”的出现也在“is not”中,我的代码无法找到:
public static void loadOperators(){
operators.add("is");
operators.add("is not");
operators.add("does not contain");
}
public static void main(String[] args) {
loadOperators();
for(String s : operators){
System.out.println(str.split(s).length - 1);
}
}
最佳答案
由于单词可能多次出现,split
无法解决您的用例,就像 is
和 is not
对您来说是不同的运算符。理想情况下,您会:
Iterate :
1. Find the index of the 'operator'.
2. Search for the next space _ or word.
3. Then update your string as substring from its index to length-1.
关于Java从句子中提取子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46299056/