Mina Makar
Mina Makar

Reputation: 51

SearchBar ignore character while filtering

I have a tableView populated with an array of type String. Some of the words in the string contain the hyphen character (-). I know I can filter a tableView and have it delete this character if I want. Is it possible to just ignore the character during a search but have it still appear in the tableView? I’m interested in filtering by exact word search and not by .contains parameters.

Example:

array = [“one”, “two”, “three-”]

person searches “t” : nothing returns

person searches “two : search returns “two”

person searches “three” : search returns “three-”

Upvotes: 1

Views: 334

Answers (1)

AaoIi
AaoIi

Reputation: 8396

There are two ways here if you want to filter using CONTAINS[c] or MATCHES, here is example with NSPredicate:

    let searchPredicate = NSPredicate(format: "SELF CONTAINS[c] %@", searchController.searchBar.text!)
    let array = (self.array as NSArray).filtered(using: searchPredicate)

Now using Contains will filter depending on the string that contains the key word as you said, so three- will be returned because user searched for three:

person searches “three” : search returns “three-”.

The other way is to use MATCHES and here is an example:

    let searchPredicate = NSPredicate(format: "SELF MATCHES %@", searchController.searchBar.text!)
    let array = (self.array as NSArray).filtered(using: searchPredicate)

Using matches will return the result if its exactly the same as the search key, if i took your example:

person searches “three” : search returns “”.

but

person searches “three-” : search returns “three-”.

Now if you want to ignore the character while displaying you can just trim it if found in cellForRow:

if string.contains("-"){
     let trimmedString = string.replacingOccurrences(of: "-", with: "")
}

At the end i think if you used contains with trimming while display, that is the best option for you.

Upvotes: 1

Related Questions