想象一下食物清单。用户搜索食物并显示与此匹配的所有食物的列表。
例如,用户搜索'apple',程序返回'red apple','green apple'等。
for (int i = 0; ; i++) {
if (foodNames[i].contains(searchTerm){
foodChoice1 = foodName[i];
break;
// then print food name
}
}
如何扩展以显示列表中的多个食物名称?代码只是当场嘲笑,可能不起作用,只是为了展示一个例子。
答案 0 :(得分:2)
如何使用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]
答案 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 :(得分:-1)
你可以简单地使用它:
String[] strArray = {"green apple", "red apple", "yellow apple"};
for (String s : strArray)
if (s.contains("apple"))
System.out.println(s);