从字符串中删除单词数组

时间:2018-10-13 14:41:57

标签: ios arrays swift string

我的数据包含某些我不想显示的单词。我正在尝试从字符串中删除这些单词集,然后再将其显示在标签上。使用我拥有的代码,我可以逐个单词地执行此操作,但是必须输入代码X次才能为每个单词实现它。一次删除一组单词的正确方法是什么?

这是我当前正在使用的代码:

 let remove = ["Production", "Productions", "Studio", "Studios", 
"Entertainment", "Pictures", "Company", "Films", "Media"]
                if let range = string.range(of: remove) {
                    string.removeSubrange(range)
                }
                self.label.text = string

使用此代码,我在range行中收到此错误:

  

参数类型'[String]'与预期类型'StringProtocol'不符

3 个答案:

答案 0 :(得分:2)

错误已清除。

range(of的参数是String而不是数组([String]

您需要循环

let wordsToRemove = ["Production", "Productions", "Studio", "Studios", "Entertainment", "Pictures", "Company", "Films", "Media"]
for word in wordsToRemove {
   if let range = string.range(of: word) {
      string.removeSubrange(range)
   }
}
self.label.text = string

另一种选择是正则表达式

let trimmedString = string.replacingOccurrences(of: "(Productions?|Studios?|Entertainment|Pictures|Company|Films|Media)",
                                             with: "",
                                          options: .regularExpression)
self.label.text = trimmedString

答案 1 :(得分:1)

您可以尝试

remove.forEach {
   if let range = string.range(of:$0) {
     string.removeSubrange(range)
  }
}

range(of:)期望字符串而不是数组

答案 2 :(得分:0)

您可以指定允许的单词,然后使用Filter删除不需要的单词:

var strings = ["Hello","Playground","World","Earth"]

var allowedStrings = "Playground Earth" // Specify using space
let seperated:[String] = allowedStrings.components(separatedBy: " ")

for i in seperated {
    if strings.contains(i) {
        strings = strings.filter{$0 != i}
    }
}
print(strings)   // ["Playground", "Earth"]