Question

I want to search through an array with strings in it. Therefore i use a searchbar. Here's my code:

for(NSString *string in itemsArray)
{
   NSRange nameRange = [string rangeOfString:text options:NSCaseInsensitiveSearch];
   if (nameRange.location != NSNotFound)
   {
      [filteredItemsArray addObject:string];
   }
}

It works great, but the problem is it just finds the string when I write it exactly the same way (except the case insensitivity). But I would also like to find it even if the strings doesn't fit a 100%. For example when I search for 'Ralle Turner' it should also find the string with 'Ralle/Ralph Turner'.

Thanks for your help guys!

Was it helpful?

Solution

You need to split the search string into words, and then iterate through each word to find a match.

You can split the string using this code inside your loop

for(NSString *string in itemsArray)
{
    NSArray *words = [text componentsSeparatedByString:@" "];
    for (NSString *word in words)
    {
        NSRange nameRange = [string rangeOfString:word options:NSCaseInsensitiveSearch];
        if (nameRange.location != NSNotFound)
        {
           [filteredItemsArray addObject:string];
           break;
        }
    }
}

OTHER TIPS

You can compute the levenshtein distance of two string to see if there is a potential match. You can easily find some implementation on the web, for instance:

-via NSString Category

-via a single method

Or use one the others approximate string matching algorithms

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top