Reputation: 3165
Does NSArray
have the capability of matching a string in an array with the closest representation of that string in another array?
For example:
NSString *search = @"apple p";
NSArray *array = [[NSArray alloc]initWithObjects:@"apple",@"apple pie",@"apple pies", @"apple juice", nil];
//Now we want to look for a similar string
[array ?];
The desired result should be: apple pie (most similar string). Any ideas how this could be done?
Upvotes: 3
Views: 239
Reputation:
You could sort the array based on similarity, then retrieve the last element in the sorted array: the most similar string. Assuming you've defined some method similarityTo:
in a category on NSString
, something like the following should do the trick:
NSInteger compareStrings(id a, id b, void *context) {
int aSimilarity = [a similarityTo:(NSString *)context];
int bSimilarity = [b similarityTo:(NSString *)context];
return aSimilarity - bSimilarity;
}
// Retrieving the most similar string.
NSString *result = [[array sortedArrayUsingFunction:compareStrings
context:search] lastObject];
Upvotes: 3