在迭代一系列诅咒词时过滤诅咒句子中的单词

时间:2017-12-14 17:15:18

标签: swift

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)

它只审查我要过滤所有数组的最后一个索引。

1 个答案:

答案 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: "****")
}