Reputation: 138
Imagine a list of foods. The user searches for a food and is presented with a list of all foods which match this.
Example, user search 'apple', program returns 'red apple', 'green apple', etc.
for (int i = 0; ; i++) {
if (foodNames[i].contains(searchTerm){
foodChoice1 = foodName[i];
break;
// then print food name
}
}
How would this be extended to show more than one food name from the list? The code was just mocked up on the spot, likely doesn't work, just to show an example.
Upvotes: 0
Views: 76
Reputation: 167
you can simply use this:
String[] strArray = {"green apple", "red apple", "yellow apple"};
for (String s : strArray)
if (s.contains("apple"))
System.out.println(s);
Upvotes: -1
Reputation: 16833
Try this :
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);
}
Upvotes: 1
Reputation: 48434
What about using a Set<String>
to store the results and comparing to lower case?
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);
Output
[Apple pie, Green APPLE, Red apple]
Upvotes: 2