我有一个字符串(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
- 这里使用
%
将字符串分割成数组 - 过滤数组以检查是否分割句子 是否包含“dog”。
- 使用
//
将生成的字符串连接成一个。
关于java - 在字符串中搜索子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56207594/