Reputation: 1659
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?
Upvotes: 0
Views: 49
Reputation: 24341
Try,
let keywordsCount = keywords.filter({ string.lowercased().contains($0.lowercased()) }).count
if keywordsCount >= keywords.count / 2 {
print("Success")
} else {
print("Failure")
}
Upvotes: 1
Reputation: 3323
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
Upvotes: 0