user3354279
user3354279

Reputation: 3

How to return all substrings (more than once) in Swift?

I have a list of words that I am trying to match into an input string in Swift. For example, each time one of these words appears in the string, I would like to print it and add one to a variable. I have gotten as far as being able to determine if the word appears in the sentence once, but not if it is in the string more than once. Here is my code...

import Swift
import Foundation

var dictionary: [String] = 
["blue",
"red",
"yellow",
"green"]

var count = dictionary.count

var string = "blue yellow red green blue red"

var value = 0

for var index = 0; index < count; index++ {
    if string.lowercaseString.rangeOfString(dictionary[index]) != nil {
            print("\(dictionary[index])")
            value++
            print("\(dictionary[index]) is a flagged word")
            print(value)
    }
}

Doing this would only put the value at 4 (should be 6), because it would only count each word once and would ignore the other blue and red substrings. Is there a workaround for this? I could not find any info on this, thanks.

Upvotes: 0

Views: 438

Answers (1)

David Berry
David Berry

Reputation: 41226

Easiest way is to combine componentsSeparatedByString and reduce:

var count = string.componentsSeparatedByString(" ").reduce(0) {
   words.contains($1) ? $0 + 1 : $0 
}

Although this doesn't do exactly the same thing as your example because it assumes your actually looking for words in your dictionary. If you're actually just looking for string matches, try:

var count2 = words.map({
    string.componentsSeparatedByString($0).count - 1
}).reduce(0, combine:+)

Upvotes: 2

Related Questions