[英]How to present a list of matching strings in string array?
想象一下食物清單。 用戶搜索食物,並顯示與之匹配的所有食物的列表。
例如,用戶搜索“蘋果”,程序返回“紅蘋果”,“綠蘋果”等。
for (int i = 0; ; i++) {
if (foodNames[i].contains(searchTerm){
foodChoice1 = foodName[i];
break;
// then print food name
}
}
如何將其擴展為顯示列表中的多個食物名稱? 該代碼只是在現場進行了模擬,可能無法正常工作,只是為了顯示一個示例。
使用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]
嘗試這個 :
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);
}
您可以簡單地使用:
String[] strArray = {"green apple", "red apple", "yellow apple"};
for (String s : strArray)
if (s.contains("apple"))
System.out.println(s);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.