简体   繁体   中英

Swift: How to check for partial occurrence of keywords in a string

I want to check if a string contains atleast two or 50% of a set of keywords.

I currently run a check for string that contains all the keywords

 var keywords = ["house","floor", "cleaner"] 
 let string = "SWIFFER WETJET FLOOR CLEANER HOUSE SOLUTION REFILL, LAVENDER, 1 CT"
 let string2 = "FABULOSO ALL PURPOSE CLEANER, LAVENDER - 169 FL OZ"

 let success = !keywords.contains(where: { !generatedString.contains($0) })

This works and returns true if all the keywords are in a string. Now I want to just check for atleast two or 50% of the keywords in the string.

so success will return true for string2 too. How can I implement a check for atleast two or 50% of the keywords in the string?

Try,

let keywordsCount = keywords.filter({ string.lowercased().contains($0.lowercased()) }).count

if keywordsCount >= keywords.count / 2 {
    print("Success")
} else {
    print("Failure")
}

Filter and count keywords which are contained within the string.

  let count = keywords.filter { generatedString.contains($0) }.count

Then compare count to two or 50% or whatever

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