拆分一个字符串,将每个单词与一个arraylist进行比较

时间:2017-01-04 21:43:10

标签: java string arraylist

我需要分割一个字符串,如"汉堡和薯条"所以我可以将所有3个单词比作填充了常用单词的ArrayList,例如"和"所以我可以删除它们并留下"汉堡"和"薯条"比较和填写食物的列表。这就是我正在玩的东西。如果我单独进入汉堡或薯条,其他if块可以工作,但我希望能够说"汉堡和薯条"并检查它们是否存在于菜单中并基本返回true。

tl; dr ...如何拆分String项并根据ArrayLists检查字符串中的每个单词。     public boolean checkItem(String item){

    // example list
    ArrayList<String> menu = new ArrayList<String>();
    menu.add("burger");
    menu.add("fries");

    // common words to check for
    ArrayList<String> common = new ArrayList(Arrays.asList("and"));

    if (/*check for common words here*/  ) {
        // delete words if any 

    }

    else if (menu.contains(/* item string here */)) { 
        System.out.println("true");
        return true;
    }

    else {
        System.out.println("false");

        return false;
    }
}

1 个答案:

答案 0 :(得分:2)

如果您确定菜单上的所有条目都是单一措辞或由其他内容分隔,那么Space就可以通过简单地按Space拆分输入来完成。

此外,您应该使用Set代替List来执行比较,因为它更快。

这是一个简单的例子,可以帮助您入门:

private void checkMenu() {
    List<String> commonWords = Arrays.asList("and", "or", "not");
    Set<String> commonSet = new HashSet<>(commonWords);

    List<String> menu = Arrays.asList("burger", "fries");
    Set<String> menuSet = new HashSet<>(menu);

    String input = "burger and fries";
    String[] tokens = input.split(" ");
    for (int x = 0; x < tokens.length; x++) {
        if (!commonSet.contains(tokens[x]) && menuSet.contains(tokens[x])) {
            System.out.println(tokens[x] + " Exist In Menu!");
        }
    }
}

如果您只是想检查菜单上是否包含所有内容,那么您可以执行以下操作:

private boolean checkMenu() {
    List<String> commonWords = Arrays.asList("and", "or", "not");
    Set<String> commonSet = new HashSet<>(commonWords);

    List<String> menu = Arrays.asList("burger", "fries");
    Set<String> menuSet = new HashSet<>(menu);

    String input = "burger and fries";
    String[] tokens = input.split(" ");
    for (int x = 0; x < tokens.length; x++) {
        if (!commonSet.contains(tokens[x]) && !menuSet.contains(tokens[x])) {
            System.out.println(tokens[x] + " Doesn't Exists On The Menu!");
            return false;
        }
    }

    System.out.println("Everything Exists On The Menu!");
    return true;
}