[英]Find a particular word in a string array of sentences and return the frequency of a particular word throughout the array
[英]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.