java - 根据单词数组检索句子

标签 java arrays

我有一串文本如下:

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/

相关文章:

Java Jsoup 网页抓取

java - 如何在JSP中为mySQL自动生成唯一ID

java - 为什么在 netbeans 项目中从 ant 命令行运行 test-with-groovy 不能运行测试?

java - 从 jar 或目录加载时文件的行为有所不同

python - 将 Pandas 索引中的分组数组元素转换为 Python 中的单个数组元素

java - 在对象数组上使用 for-each - "Integer[] array"- 为什么 "for(int i : array)"有效?

Java 套接字 API : How to tell if a connection has been closed?

javascript - 无法在循环外访问数组元素

javascript - 从js中的两个数组中删除重复的哈希?

C# 在二维大数组中查找二维小数组