首页 > 解决方案 > 在字符串中搜索子字符串

问题描述

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

预期输出:

我的狗在哪里,约翰?// 你的狗在桌子上 // 养一只好狗”

标签: javastringsearchsubstringstring-search

解决方案


您可以使用:

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

这使:

我的狗在哪里,约翰?// 你的狗在桌子上 // 养一只好狗


  1. 在这里,字符串通过使用拆分为一个数组%
  2. 过滤数组以检查拆分句子是否包含“dog”。
  3. 使用 . 将生成的字符串连接成一个//

推荐阅读