检查String数组是否包含另一个String Array中的单词

问题描述 投票:-1回答:2

无法弄清楚如何检查来自一个字符串数组的单词是否在另一个字符串数组中。这是我到目前为止:

        FileInputStream fis = new FileInputStream("TranHistory.csv");
        InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
        CSVReader reader = new CSVReader(isr);

        String[] groceries = new String[]{"albertsons", "costco"};

        for (String[] cols; (cols = reader.readNext()) != null;) {
            if(cols[4].toLowerCase().contains(groceries)){
                System.out.print(cols[4]);
            }

        }

上面的代码目前给我一个错误,因为.contains()不能应用于String Array。这仅在我将if语句更改为此时才有效:

        if(cols[4].toLowerCase().contains("albertsons")){
                System.out.print(cols[4]);
        }

我的问题是String []杂货会有很多杂货店,所以我认为比较String [] col和String []杂货是最有效的方法,我只是在实现它时遇到了麻烦。

解:

我想通了......你必须做一个嵌套的for循环。这就是我做的:

String[] groceries = {"albertsons", "costco"};

for (String[] cols; (cols = reader.readNext()) != null;) {
      for (int i = 0; i < groceries.length; i++){

          if(cols[4].toLowerCase().contains(groceries[i]))
             {
                 System.out.print(cols[4]);
                 }

           }
      }
java arrays string
2个回答
2
投票

我建议创建一个包含您计划拥有的所有杂货的Set<String>

Set<String> groceries = Set.of("albertsons", "costco");

for (String[] cols; (cols = reader.readNext()) != null;) {
    if (groceries.contains(cols[4].toLowerCase()){
        System.out.print(cols[4]);
    }
}

Set中搜索不会像使用数组那样采用线性时间。

正如YCF_L和我在下面的评论中解释的那样,您可以使用以下命令初始化Java 8中的Set

Set<String> groceries = new HashSet<>(Arrays.asList("albertsons", "costco"));

0
投票

我通常会通过Hashset来做这件事,因为它在恒定时间而不是线性时间内搜索元素。因此,您可以使用此代码进行搜索。我假设你想要找到文件中的整个原始数组。

FileInputStream fis = new FileInputStream("TranHistory.csv");
InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
CSVReader reader = new CSVReader(isr);

String[] groceries = new String[]{"albertsons", "costco"};
Set<String> grocerySet = Arrays.stream(groceries).collect(Collectors.toSet());
System.out.println(grocerySet);
for (String[] cols; (cols = reader.readNext()) != null;) {
    Set<String> smallGrocerySet = Arrays.stream(cols).collect(Collectors.toSet());
    if(grocerySet.containsAll(smallGrocerySet)){
        System.out.println(Arrays.toString(cols));
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.