0

I am working on an iOS project where I am using a custom search bar. I am stuck at a point where I want to be able to search for a text like 093-003 even if I type in 093003 or 093 003 in the search bar.

This is where I am comparing the strings.

 NSArray *tempAccountArray = _searchBarText.length > 0 ? 
[[WBCBusinessLogic sharedInstance].internalAccountsArray 
filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"displayName CONTAINS[cd] %@ || displayNumber LIKE %@", _searchBarText, _searchBarText]]:
[WBCBusinessLogic sharedInstance].internalAccountsArray; 
Somya
  • 65
  • 1
  • 7

2 Answers2

0

What you are asking for is quite straightforward to do. You need a string compare function that ignores spaces and hyphens. So we do the following :

  • First strip both strings of spaces and hyphens
  • Compare if they are equal and return the result.

    -(BOOL)doStringsMatch:(NSString*)first second:(NSString*)second
    {
         NSCharacterSet *skip = [NSCharacterSet characterSetWithCharactersInString:@"- "];
    
      return ([[first stringByTrimmingCharactersInSet:skip] isEqual:[second stringByTrimmingCharactersInSet:skip]]);
    
    }
    

EDIT: This only trims the characters from the beginning or end of the string. For a much cleaner solution using regexes: https://stackoverflow.com/a/13177885/1616513

Community
  • 1
  • 1
Samhan Salahuddin
  • 2,140
  • 1
  • 17
  • 24
  • stringByTrimmingCharacterInSet will only trim the characters from the beginning or end of the string. It is better to use stringByReplacingOccurencesOfString. Thanks for the help :) – Somya Aug 31 '15 at 10:46
  • You're right. I missed out in the hurry :D. But I'd suggest you use a regex instead. It's much cleaner.http://stackoverflow.com/a/13177885/1616513 – Samhan Salahuddin Sep 01 '15 at 06:38
0

This is the method I used to compare the strings-

-(BOOL)doStringsMatch:(NSString*)first second:(NSString*)second
{
    first = [first stringByReplacingOccurrencesOfString:@"-" withString:@""];
    first = [first stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSLog(@"First String: %@", first);

    second = [second stringByReplacingOccurrencesOfString:@"-" withString:@""];
    second = [second stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSLog(@"Second String: %@", second);

    return ([first isEqual:second]);
}
Somya
  • 65
  • 1
  • 7