searching array elements within another array
I am developing an iphone app where users input a few words and I then need to look them up (if they exist basically) in a local hard coded long array of words (my case is more complex to explain, but lets say a user is entering 5 names of cities and I need to look up my array of cities and let him know which onces exist).
What would be the best way to go about this problem? especially since some of the names may be found in a sentence format (for example, someone can enter: "the city of paris", but I have "Paris", so its still good).
Is there any good 3rd part lib for that maybe? I can definitely try to do that manually, but I am sure there are some better solutions.
Thanks.
I'd use NSPredicate:
NSString *searchText = @"paris"; //user's input
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self LIKE[c] %@", searchText];
NSArray *results = [yourHardcodedArrayOfCities filteredArrayUsingPredicate:predicate];
This will fill *results with any matching results from your main array. The [c] in the predicate specifies case insensitivity, so Paris will match paris or pArIs.
Edited to add
Instead of using LIKE in the predicate (as shown in my original answer), it is easier to use CONTAINS to find matches if your search text is a sentence. So, you could use:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self CONTAINS[c] %@", searchText];
Same result, but a bit easier. This way, if the search string is "New York City" or "City of New York" it will still match on your hardcoded entry of "New York".
Here is an Apple doc on using predicates which you might find useful: http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Predicates/Articles/pUsing.html
Using std::string's find
userInput and predefinedPhrase are both std::string
for userInput in userInputList
for predefinedPhrase in your predefinedPhraseSet
test userInput.find(predefinedPhrase);
I first tried to avoid iterating over your predefinedPhraseSet, since it might be large.
But I guess there's no other way, the other solution (with predicate) seems to do that as well.
下一篇: 搜索另一个数组中的数组元素