gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 09:52:42 24 4
gpt4 key购买 nike

我有一个字符串(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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com