简体   繁体   中英

Search in String word by word

I have an array of type [Patient] with the structure of the following struct:

struct Patients {
    var name: String
    var lastName: String
    var age: Int
    var indexed: String  
}

The var "indexed" is equals to:

name + " " + lastName + " " + age

I have a searchTextField that searchs in the array by filtering results:

let search = self.searchText.stringValue

return arrayOfPatients.filter(){
    $0.index.localizedStandardContains(search)
}

If I have these lines in the array.indexed:

Jon McDonalds 18 
Jon Gomez 18 
Jon Gomez 37 
Tom Gomez 28

If I search "Jon 18" it returns no results. Or if I search for "Gomez Jon" it returns no results.

I want to search, for example "18 Jon" and retrieve all patients named Jon with 18 years old.

How can I improve my algorithm to search strings word by word, ignoring spaces?

Check if this works for you. Basically each word of the searching string is compared to each word of the indexed property of each Patient.

If the indexed property has all the words from the searching string then it returns true.

在此处输入图片说明

Here is the relevant code:

let searchStringSeparated = search.components(separatedBy: " ")

let results = arrayOfPatients.filter(){ patient in
    !searchStringSeparated.map{ word in
        patient.indexed.components(separatedBy: " ").map{
            $0.localizedStandardContains(word)
        }.contains(true)
    }.contains(false)
}

The code is incredibly fast, concise and efficient. The only "bug" is that when I introduce an space in my searchTextField, it interpretates that space as an empty word, so in the searchStringSeparated the return value is, for example:

["Jon", ""]

So, the result is nil. It was neccesary to add this code to the function:

let lastIndexOfSearchStringsArray = searchStringsSeparated.count - 1
if searchStringSeparated[lastIndexOfSearchStringsArray] == "" {
    searchStringSeparated.removeLast()
    } else { 
}

Thank you so so much for your answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM