有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在字符串数组中显示匹配字符串的列表?

想象一张食物清单。用户搜索一种食物,并显示与此匹配的所有食物的列表

例如,用户搜索“苹果”,程序返回“红苹果”、“绿苹果”等

for (int i = 0; ; i++) {
     if (foodNames[i].contains(searchTerm){
         foodChoice1 = foodName[i];
         break;
         // then print food name
     }
}

如何将其扩展以显示列表中的多个食品名称?代码只是在现场进行了模拟,可能不起作用,只是为了展示一个示例


共 (3) 个答案

  1. # 1 楼答案

    试试这个:

    List<String> matchingFood = new ArrayList<String>();
    for (int i = 0; i < foodNames.length; i++) {
        if (foodNames[i].contains(searchTerm)
        {
             matchingFood.add(foodName[i]);
        }
    }
    System.out.println("Food matching '" + searchTerm + "' :");
    for (String f : matchingFood)
    {
        system.out.prinln(f);
    }
    
  2. # 2 楼答案

    您可以简单地使用:

    String[] strArray = {"green apple", "red apple", "yellow apple"};
    for (String s : strArray)
        if (s.contains("apple"))
            System.out.println(s);
    
  3. # 3 楼答案

    使用Set<String>存储结果并与小写进行比较怎么样

    String[] foods = {
        "Red apple", "Green APPLE", "Apple pie", 
        "Lobster Thermidor Sausage and SPAM"
    };
    String query = "apple";
    String queryTLC = query.toLowerCase();
    // sorting result set lexicographically
    Set<String> results = new TreeSet<String>();
    for (String food: foods) {
        if (food.toLowerCase().contains(queryTLC)) {
            results.add(food);
        }
    }
    System.out.println(results);
    

    输出

    [Apple pie, Green APPLE, Red apple]