【问题标题】:Splitting a string to compare each word to an arraylist [closed]拆分字符串以将每个单词与数组列表进行比较 [关闭]
【发布时间】:2017-01-04 21:43:09
【问题描述】:

我需要拆分一个字符串,例如“burger and fries”,这样我就可以将所有 3 个单词与 ArrayList 中的常用单词(例如“and”)进行比较,这样我就可以删除它们,只剩下“burger”和“薯条”进行比较并列出充满食物的物品。这就是我正在玩的东西。如果我单独输入汉堡或薯条,则 else if 块有效,但我希望能够说“汉堡和薯条”并检查它们是否存在于菜单中并基本上返回 true。

tl;dr... 如何拆分字符串项并根据 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;
    }
}

【问题讨论】:

  • 你有什么问题?
  • 这是家庭作业吗?
  • 您要检查所有项是否为菜单项,或者任何项是否为菜单项?
  • 谢谢大家,其实我想通了哈哈。我会把这个记下来。不过感谢您的快速回复!

标签: java string arraylist


【解决方案1】:

如果您确定菜单上的所有条目都是单字或由其他内容分隔,然后是 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;
}

【讨论】:

    猜你喜欢
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    • 2020-04-15
    • 2017-09-10
    • 2012-11-07
    • 2021-05-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多