我已阅读其他主题,但他们似乎只处理单个字符分隔符,我认为Playground正在崩溃,因为我使用了多个字符。
"[0, 1, 2, 1]".characters
.split(isSeparator: {[",", "[", "]"].contains($0)}))
.map(String.init) //["0", " 1", " 2", " 1"]
有点工作,但我想用“,”而不是“,”。显然我可以使用[“,”,“”,“[”,“]”]并抛出空格但是当我只想要删除字符串模式时呢?
简而言之:如何将Swift字符串与其他较小的字符串分开?
答案 0 :(得分:5)
Swift 3
+
Swift 2
let s = "[0, 1, 2, 1]"
let splitted = s.characters.split { [",", "[", "]"].contains(String($0)) }
let trimmed = splitted.map { String($0).trimmingCharacters(in: .whitespaces) }
结果是一个没有多余空格的字符串数组:
[" 0"," 1"," 2"," 1"]
答案 1 :(得分:1)
有几种可能性浮现在脑海中。如果您可以使用字符作为分隔符:
let str = "[0, 1, 2, 1]"
let separatorSet = NSCharacterSet(charactersInString: ",[]")
let comps = str.componentsSeparatedByCharactersInSet(separatorSet).filter({return !$0.isEmpty})
这会产生
[“0”,“1”,“2”,“1”]
如有必要,可以使用stringByTrimmingCharactersInSet
映射或向separatorSet
添加空格来删除空格。
或者如果你真的需要使用字符串作为分隔符:
let str = "[0, 1, 2, 1]"
let separators = [", ", "[", "]"]
let comps = separators.reduce([str]) { (comps, separator) in
return comps.flatMap { return $0.componentsSeparatedByString(separator) }.filter({return !$0.isEmpty})
}
哪个收益率:
[“0”,“1”,“2”,“1”]