snksnk
snksnk

Reputation: 1595

search character sequence with UISearchBar

I have a searchBar and a searchController in my project. I want to be able to search for a specific sequence of letters and possibly skipping a character or two if possible. For example if I search for "iPhone" or "i-phone" or "i phone" or "piphone" or "phone" i want to be able to still find the search term "iphone" in the list. Any help would be appreciated.

Where searchTerm is an all uppercase string from UISearchBar

NSCharacterSet *allowedChars = [[NSCharacterSet characterSetWithCharactersInString:@" ABCDEFGHIJKLMNOPQRSTUVWXYZ 1234567890"] invertedSet];
NSString *resultString = [[searchTerm componentsSeparatedByCharactersInSet:allowedChars] componentsJoinedByString:@" "];

Taking in mind that the @" " in the allowsChars is essential because the actual search could be @"iPhone 32gb" etc...

Upvotes: 0

Views: 327

Answers (1)

Muruganandham K
Muruganandham K

Reputation: 5331

    NSArray *firstNames = [[NSArray alloc] initWithObjects: @"i-phone", @"i phone", @"phone", @"Quentin",@"apple phone",@"phoapple" ];
    NSString * searchStr = @"phone";
    NSPredicate *thirtiesPredicate = [NSPredicate predicateWithFormat:@"SELF CONTAINS[cd] %@",searchStr];
    NSLog(@"Bobs: %@", [firstNames filteredArrayUsingPredicate:thirtiesPredicate]);

It will log as

2014-02-18 06:09:52.911 demo[5261] Bobs: ("i-phone", "i phone", phone, "apple phone")

Upvotes: 1

Related Questions