e.iluf
e.iluf

Reputation: 1659

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?

Upvotes: 0

Views: 49

Answers (2)

PGDev
PGDev

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

Dale
Dale

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

Related Questions