java - 在字符串中搜索子字符串
问题描述
我有一个字符串(Str),其中的短语由一个字符分隔(为了简单理解,我们将其定义为“%”)。我想在这个字符串(Str)中搜索包含一个单词(如“dog”)的短语并将该短语放入一个新字符串中
我想知道一个好的/好方法来做到这一点。
Str 是我要搜索的字符串,“Dog”是我要搜索的单词,%
是行分隔符。
我已经有了阅读器、解析器以及如何保存该文件。如果有人找到我的简单搜索方法,我将不胜感激。我可以做到,但我认为这太复杂了,而实际的解决方案非常简单。
我曾考虑lastIndexOf("dog")
在子字符串中搜索并搜索“%”,Str(0, lastIndexOf("dog")
然后再搜索第二个 % 以获得我正在搜索的行。
PS:Str中可能有两个“狗”,我希望所有显示“狗”字样的行
例子:
Str = " Where is my dog, john ? % your dog is on the table % really thanks john % you're welcome % 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
这使:
我的狗在哪里,约翰?// 你的狗在桌子上 // 养一只好狗
- 在这里,字符串通过使用拆分为一个数组
%
- 过滤数组以检查拆分句子是否包含“dog”。
- 使用 . 将生成的字符串连接成一个
//
。
推荐阅读
- angular - 错误 TS1005: '(' 预期在具有新 Date() 的对象类型脚本中
- microcontroller - 如何访问 Jamara 038300 qcr?
- python - 使用 Model @property 装饰器来检查 manytomany 的计数
- java - ObjectOutputStream 和 ObjectInputStream 结果不匹配
- javascript - 如何在 Python 中更新散景的 JavaScript 回调中的源?
- react-native - 反应本机日期选择器仅在调试模式下工作
- mysql - 在 JSON 字段的数组中搜索具有缺失属性的记录 (MySQL)
- python - **HTMLltestrunner 支持哪些版本的python**
- spring-amqp - spring-retry:长时间等待是否安全?(半小时等)
- php - 从 XAMPP 迁移到 Webhost