【发布时间】:2016-03-12 16:05:41
【问题描述】:
我有一个 Java 代码,可以根据单词数组检索句子。 文本字符串:
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 word "text" and "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);
}
}
}
}
但是,如果句子包含数组中的两个单词,它将打印该句子两次。例如:
The text is nice //contains: text
The text is nice//contains: nice.
如何只打印一次句子? 谢谢。
【问题讨论】:
-
那么当你只打印一次句子时,你是否希望它包含的所有单词也都打印出来?
-
是的,只检索数组中具有指定单词的句子,并列出句子中找到的所有单词。
-
发表了我的答案。看看吧。