我有一串文本如下:
String text = "This is a sample text. Simple yet elegant. Everyone dies. I don't care. This text is nice.";
我还有一个单词数组,如下所示:
String[] words = new String[] {"text", "care", "nice"};
现在,我需要获取数组中包含特定单词的句子。因此,要输出的句子应该包含单词“text”、“care”或“nice”。结果输出应如下所示:
This is a sample text. //contains the word "text"
I don't care. //contains the word "care"
This text is nice. //contains the "nice"
为此,我尝试将每个句子存储在一个数组String[]句子
中,该数组将产生如下输出:
[This, is, a, sample, text], [Simple, yet, elegant] , [Everyone, dies], [I, don't, care], [This, text, is, nice]
不知道下一步该去哪里。感谢帮助。
最佳答案
你可以尝试这样的事情:
public static void main(String[] args) {
String text = "This is a sample text. Simple yet elegant. Everyone dies. I don't care. This text is nice.";
String[] words = new String[] {"text", "care", "nice"};
String[] parts = text.split("\\.");
for(String w: words){
for(String sentence: parts){
if(sentence.contains(w)){
System.out.println(sentence +" //contains: "+w);
}
}
}
}
输出:
This is a sample text //contains: text
This text is nice //contains: text
I don't care //contains: care
This text is nice //contains: nice
关于java - 根据单词数组检索句子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35939364/