java - 在字符串中搜索子字符串

标签 java string search substring string-search

我有一个字符串(Str),其中的短语由字符分隔(为了简单理解,我们将其定义为“%”)。我想在此字符串 (Str) 中搜索包含单词(如“dog”)的短语,并将该短语放入新字符串中

我想知道有什么好的/很棒的方法可以做到这一点。

Str 是我要搜索的字符串,“Dog”是我要搜​​索的单词,% 是行分隔符。

我已经有了阅读器、解析器以及如何保存该文件。如果有人为我找到一种简单的搜索方法,我将不胜感激。我可以做到,但我认为这太复杂了,而实际的解决方案却很简单。

我曾考虑过搜索 lastIndexOf("dog") 并在 Str(0, lastIndexOf("dog")) 的子字符串中搜索“%” 然后第二个 % 来获取我正在搜索的行。

P.S:Str 中可能有两个“dog”,我希望所有显示“dog”一词的行

示例:

Str = " Where is my dog, john ? % your dog is on the table % really thanks john % you're welcome % Have a nice dog"

预期输出:

Where is my dog, john ? // your dog is on the table // Have a nice dog"

最佳答案

您可以使用:

String str = "Where is my dog, john ? % your dog is on the table % really thanks john " +
             "% you're welcome % Have a nice dog";

String dogString = Arrays.stream(str.split("%"))            // String[]  
                     .filter(s -> s.contains("dog"))        // check if each string has dog
                     .collect(Collectors.joining("//"));    // collect to one string

给出:

Where is my dog, john ? // your dog is on the table // Have a nice dog

<小时/>
  1. 这里使用%将字符串分割成数组
  2. 过滤数组以检查是否分割句子 是否包含“dog”。
  3. 使用 // 将生成的字符串连接成一个。

关于java - 在字符串中搜索子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56207594/

相关文章:

JavaScript 案例 : "look at" + item

mysql - 使用 spring thymeleaf MVC 进行表单搜索?

sql - SQL中根据 "First Name"+ "Last Name"过滤行

regex - 使用 MongoDB 和 Mongoose 在多个字段中搜索子字符串

c++ - 我怎样才能从控制台读取密码,呼应 splats?

java - 您的 SQL 语法有误;查看与您的 MySQL 服务器对应的手册

java - Jersey 如何注释 java.sql.Timestamp 对象

java - Java 中的阿姆斯特朗号码检查

java - 通用列表的深拷贝

python - 如何在python中获取字符串x之后的所有内容