删除字符串中的特定子字符串[Swift]

xxm*_*exx 12 string swift

我有一个字符串var m = "I random don't like confusing random code."我想删除字符串中的所有子random字符串实例m,返回parsed完成删除的字符串.

最终结果将是: parsed = "I don't like confusing code."

我将如何在Swift 3.0+中执行此操作?

ldi*_*ndu 31

这很简单,有很多方法可以用空字符串替换字符串"random"

let parsed = m.replacingOccurrences(of: "random", with: "")
Run Code Online (Sandbox Code Playgroud)


Cod*_*ent 10

取决于您希望替换的复杂程度(在 之后删除/保留标点符号random)。如果要删除random并可选地删除其后面的空间:

var m = "I random don't like confusing random code."
m = m.replacingOccurrences(of: "random ?", with: "", options: [.caseInsensitive, .regularExpression])
Run Code Online (Sandbox Code Playgroud)