var myDirtySentence = """
Some dirty words like
bleep and
bloop
"""
var notAllowedWords = ["bleep","bloop"]
var myCleanSentence = ""
for i in 0..<notAllowedWords.count{
myCleanSentence = myDirtySentence.replacingOccurrences(of:notAllowedWords[i], with: "****")
}
print(myCleanSentence)
它只审查我要过滤所有数组的最后一个索引。
答案 0 :(得分:0)
有几件事。首先,您需要从notAllowedWords的索引0
开始。你也没有保存每次传递的结果,所以尝试这样的事情:
var myDirtySentence = """
Some dirty words like
bleep and
bloop
"""
var notAllowedWords = ["bleep","bloop"]
var myCleanSentence = myDirtySentence
for i in 0..<notAllowedWords.count{
myCleanSentence = myCleanSentence.replacingOccurrences(of:notAllowedWords[i], with: "****")
}
print(myCleanSentence)
我们也可以通过直接迭代notAllowedWords
来完全避免处理索引。例如:
for badWord in notAllowedWords {
myCleanSentence = myCleanSentence.replacingOccurrences(of:badWord, with: "****")
}