假设我有一个包含单个String的String类型的变量。在此字符串中,有1个或多个单词。我也有一系列字符串。我想检查数组的字符串,查找并替换数组中的单词。
例如,单词"能够"在数组中。单词"能"也在String变量中。我希望这个词可以替换为" +"字符。
我试过这样的事:
//stopWords = array of Strings / keywords = String variable
for words in stopWords {
keywordsFormatted = keywords.replacingOccurrences(of: words, with: "+", options: .regularExpression, range: nil)
}
这并没有改变任何事情。我还尝试过一段时间,还有其他一些方法,我现在甚至不想回想起来。任何帮助表示赞赏
答案 0 :(得分:4)
鉴于
let result = keywords
.components(separatedBy: " ")
.map { stopWordsSet.contains($0) ? "+" : $0 }
.joined(separator: " ")
让我们创建一个
print(result) // The sky is + not +
最后让我们解决问题
"The sky is blue, not green"
哦......让我们测试一下
,
请注意,此解决方案区分大小写。此外,关键字中的单词不会被空格分隔,因此无效。例如。由于
didSet
。{/ 1>,var keywords = "The sky is blue not green" { didSet { // if keywords is not empty, set the myTextField.text to keywords if !keywords.characters.isEmpty { myTextField.text = keywords } } }
将无法正常运作
Adrian的附录:
如果您想更新textField,只需使用{{1}},如下所示:
{{1}}