簡體   English   中英

在句子數組中查找特定單詞並返回包含該單詞的句子

[英]Find a particular word in array of sentences and return the sentences that contain the word

輸入是字符串數組,如下所示,

示例日志行:001 555 3334523 AppName 2341 這是一條消息。 001 1224 3334524443 AppSecond 2341 這是一條消息 blah 341""-*。 022201 55555 3333334523 AppThird 2341 這是其他消息。 0301 533555 3334523 AppName 2341 這是另一條消息。

我需要打印其中包含AppName的所有行。

這是我試過的。

  public static void findArrayString(String[] input, String item)
  {
    for(int i = 0; i < input.length; i++)
     {

      List<String> chr = new ArrayList<>();
        chr = Arrays.asList(input[i]);

      if(chr.get(i).contains(item))
      {
        System.out.println(input[i]);
      }

    }
  }

  public static void main(String[] args) 
  {
    String[] str = {"001 555 3334523 AppName 2341 This is a message.",
                   "001 1224 3334524443 AppSecond 2341 This is a message blah 341-*.",
                   "022201 55555 3333334523 AppThird 2341 This is some other message.",
                    "0301 533555 3334523 AppName 2341 This is another message."};

    findArrayString(str,"AppName");

  }
}

My output is :

001 555 3334523 AppName 2341 This is a message.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1
    at java.base/java.util.Arrays$ArrayList.get(Arrays.java:4351)
    at Solution.findArrayString(Solution.java:31)
    at Solution.main(Solution.java:47)

誰能告訴我哪里出錯了?

  List<String> chr = new ArrayList<>();
  chr = Arrays.asList(input[i]);

創建一個包含單個元素的列表。 但是之后

if(chr.get(i).contains(item))

嘗試找到chr的第i個元素。 因為只有一個元素,當i > 0 時拋出異常。

不需要中間列表 - 在循環中嘗試這樣的事情:

  if(input[i].contains(item))
  {
    System.out.println(input[i]);
  }

您正在使用一個 for 循環將段落分成句子,但是為了將句子分成單詞,您需要使用另一個 for 循環以便可以對單詞進行比較。這是代碼中需要的更正:

public static void findArrayString(String[] input, String item)
      {
        for(int i = 0; i < input.length; i++)
         {

          List<String> chr = new ArrayList<>();
            chr = Arrays.asList(input[i]);

            for(int j=0;j<chr.size();j++) {
                if(chr.get(j).contains(item))
              {
                System.out.println(input[i]);
              }
            }      
        }
      }

簡單的答案

class Solution
{
  public static void main(String[] args)
  {
    String s = "001 555 3334523 AppName 2341\" This is a message. 001 1224 3334524443 AppSecond 2341 This is a message blah 341\"\"-*. 022201 55555 3333334523 AppThird 2341 This is some other message. 0301 533555 3334523 AppName 2341 This is another message.";
    
    String[] str = s.split("\\.");
    for(String st : str)
    {
      if(st.contains("AppName"))
      {
      System.out.println(st);
      }
    }
    
  }
  
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM