I'm trying to filter an array of strings and return the strings that match based on two use cases.
Case 1: Only match if the searchString is at the beginning of the word.
For eg, if we have an array -> ["Ralph Breaks The Internet", "Bohemian Rhapsody", "Spider-Man: Into the Spider-Verse"] and we are trying to match it with a search string "r"
In this case, we should return ["Ralph Breaks The Internet", "Bohemian Rhapsody"] as "r" is at the beginning as in r in ralph and r in rhapsody. But "Spider-Man: Into the Spider-Verse" is not matched as the r is in the middle.
Case 2: Also match if the order of searchText is not exact.
For eg, if we have an array -> ["Ralph Breaks The Internet", "Bohemian Rhapsody", "Spider-Man: Into the Spider-Verse"] and we are trying to match it with a search string "Rhapsody Bohemian", it should still match even though the order is not the same.
Here's what I have tried so far:
func searchMovies(_ movieNames: [String], with searchText: String) -> [String] {
var matchedMovies = [String]()
for movie in movieNames {
let movieWords = movie.split(separator: " ")
let searchTextWords = searchText.split(separator: " ")
var count = searchTextWords.count
loop:
for word in movieWords {
for text in searchTextWords {
let pattern = "\\b\(text)"
if let _ = word.range(of: pattern, options: [.regularExpression, .caseInsensitive]) {
count -= 1
}
if count == 0 {
matchedMovies.append(movie)
break loop
}
}
}
}
return matchedMovies
}
I'm aware this is not an efficient way to do this. It would be great if someone can direct me in some direction so that I can solve the same thing more efficiently.