mike_89
mike_89

Reputation: 33

Return a the matched words as string from two different string in Swift

I have: str1 = "this is the first day in my work" and str2 = "this is a great day" and I want to return the matched words as string from the previous two strings str1 & str2 and then store them in a new variable

The new variable str3: String should have this text "this is day"

I have found this in my searching but i need to return a string with matches ..

func isAnagram() -> Bool {

    let str1 = "this is the first day in my work"
    let str2 = "this is a great day"

    func countedSet(string: String) -> NSCountedSet {
        let array = string.map { (character) -> String in
            return String(character)
        }
        return NSCountedSet(array: array)
    }
    return countedSet(string: str1).isEqual(countedSet(string: str2))
}

Upvotes: 2

Views: 345

Answers (2)

Leo Dabus
Leo Dabus

Reputation: 236508

You can use String method enumerateSubstrings(in: Range) using .byWords options to get the words in your string sentences and use filter to remove the words no contained in the second string:

extension StringProtocol where Index == String.Index {
    var words: [String] {
        var result: [String] = []
        enumerateSubstrings(in: startIndex..., options: .byWords) { (substring, _, _, _) in
            result.append(substring!)
        }
        return result
    }
    func matchingWords(in string: String) -> [String] {
        return string.words.filter(words.contains)
    }
}

Note that this preserves the order of occurrences and doesn't fail if there is punctuation in the string:

let str1 = "this is the first day in my work"
let str2 = "this is a great day"

let matchingWords = str1.matchingWords(in: str2)  // ["this", "is", "day"]

let str3 = matchingWords.joined(separator: " ")   // "this is day"

Upvotes: 0

Christoph
Christoph

Reputation: 722

If order in the final string doesn't matter, this would be an easy solution:

let str1 = "this is the first day in my work"
let str2 = "this is a great day"

let words1 = Set(str1.split(separator: " "))
let words2 = Set(str2.split(separator: " "))

let str3 = words1.intersection(words2).reduce("") { $0 + $1 + " "}

If order matters:

...
let str3 = words1.intersection(words2).sorted {
    words1.index(of: $0)! < words1.index(of: $1)!
}.reduce("") { $0 + $1 + " "}

Upvotes: 1

Related Questions