【发布时间】:2020-09-11 20:08:32
【问题描述】:
这是我的问题,我有一个字符串数组,其中包含一堆 国家:
让 myCountryStart = ["Africa/ABC", "America/BBC", "Asia/CBC", "Pacific/CBA", "Europe/CBB", "Indian/CAB"]
是否有任何解决方案可以删除特定单词,例如 “非洲”、“美国”、“亚洲”……等等。 让输出结果如下所示:
让 myCountryEnd = ["ABC", "BBC", "CBC", "CBA", "CBB", "CAB"]
这是我现在的代码...
let 1stReplace = myCountryStart.replacingOccurrences(of: "/", with: "", options: .literal)
let 2ndReplace = 1stReplace.replacingOccurrences(of: "Africa", with: "", options: .literal)
let 3rdReplace = 2ndReplace.replacingOccurrences(of: "Asia", with: "", options: .literal)
我知道这是一个愚蠢的解决方案。因此,我更喜欢使用 NSRegular Expression。但是我遇到了一个问题 关于字符串和字符串数组的问题。
let target = myCountryStart
let regex = "/"
let RE = try? NSRegularExpression(pattern: "regex", options: .caseInsensitive)
let modified = RE?.stringByReplacingMatches(in: target, options: .reportProgress, range: nil, withTemplate: "") {
return modified
}
let myCountryEnd = modified
因此,我收到一条警告说我不能在 String 上使用此方法 大批。我该怎么做才能解决它?
任何建议或帮助将不胜感激。感谢 Swift 菜鸟。
【问题讨论】:
-
myCountryStart似乎只有一个元素。这是真的吗? -
旧代码中的
outputStr是什么?为什么不在新代码中使用它,而不是myCountryStart? -
应该是一个字符串数组的六个元素。我忘记修改了。
-
@Sweeper 感谢您通知我有关旧代码错误的信息。
-
您没有在编辑中将其更改为 6 个元素...
标签: ios arrays swift regex string