【问题标题】:Searching in a string a substring在字符串中搜索子字符串
【发布时间】:2019-10-06 00:52:17
【问题描述】:

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

我想知道一个好的/好方法来做到这一点。

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

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

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

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

例子:

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

预期输出:

我的狗在哪里,约翰? // 你的狗在桌子上 // 祝你愉快 狗”

【问题讨论】:

  • Eric Lippert 写了一篇很棒的文章,名为Find a simpler problem。在这种情况下,您可以轻松地将问题分解为两个问题:首先,提取可能是所需输出的子字符串(即,将您的输入拆分为 % 字符),其次,将可能的字符串列表过滤为仅那些包含"dog" 的字符串。如果你能解决这两个问题,那么你就可以解决综合问题。
  • 到目前为止你有什么代码?没有这个,我们就没有帮助你的意义。当你认为你可以做到时:你为什么不简单地尝试回来?如果您有一个字符串,其中有多行以 % 分隔,那么您可以将其拆分。然后你可以检查每一行是否包含狗。

标签: java string search substring string-search


【解决方案1】:

试试这个代码。

Solution is Split from "%",然后检查它是否包含我们需要的确切单词。

public static void main(String []args){

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

     String[] words = str.split("%");
     String output = "";
     for (String word : words) {
        if (word.contains("dog")) {
            if(!output.equals("")) output += " // ";
            output += word ;
        }
     }
     System.out.print(output);
 }

【讨论】:

    【解决方案2】:

    你可以使用:

    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. 这里使用%将String拆分成一个数组
    2. 数组被过滤以检查split语句是否 是否包含“狗”。
    3. 使用// 将生成的字符串连接为一个。

    【讨论】:

      猜你喜欢
      • 2021-04-25
      • 2011-07-04
      • 1970-01-01
      • 1970-01-01
      • 2017-02-09
      • 2016-11-30
      相关资源
      最近更新 更多