在 Swift 中拆分具有多个字符的字符串

Split String with more than one character in Swift

我读过其他线程,但它们似乎只处理单个字符定界符,而且我认为 Playground 对我来说崩溃了,因为我使用了多个字符。

"[0, 1, 2, 1]".characters
              .split(isSeparator: {[",", "[", "]"].contains([=11=])}))
              .map(String.init) //["0", " 1", " 2", " 1"]

有点用,但我想使用“,”而不是“,”。显然我可以使用 [",", " ", "[", "]"] 并且这样会抛出空格,但是当我只想删除字符串模式时呢?

简而言之:如何将 Swift 字符串恰好与其他较小的字符串分开?

Swift 3

let s = "[0, 1, 2, 1]"
let splitted = s.characters.split { [",", "[", "]"].contains(String([=10=])) }
let trimmed = splitted.map { String([=10=]).trimmingCharacters(in: .whitespaces) }

Swift 2

let s = "[0, 1, 2, 1]"
let charset = NSCharacterSet.whitespaceCharacterSet()
let splitted = s.characters.split(isSeparator: {[",", "[", "]"].contains([=11=])})
let trimmed = splitted.map { String([=11=]).stringByTrimmingCharactersInSet(charset) }

结果是一个没有多余空格的字符串数组:

["0", "1", "2", "1"]

有几种可能性spring。如果可以使用字符作为分隔符:

let str = "[0, 1, 2, 1]"
let separatorSet = NSCharacterSet(charactersInString: ",[]")
let comps = str.componentsSeparatedByCharactersInSet(separatorSet).filter({return ![=10=].isEmpty})

这会产生

["0", " 1", " 2", "1"]

如有必要,可以通过使用 stringByTrimmingCharactersInSet 映射或向 separatorSet 添加 space 来删除 space。

或者如果您确实需要使用字符串作为分隔符:

let str = "[0, 1, 2, 1]"
let separators = [", ", "[", "]"]
let comps = separators.reduce([str]) { (comps, separator) in
    return comps.flatMap { return [=11=].componentsSeparatedByString(separator) }.filter({return ![=11=].isEmpty})
}

产生:

["0", "1", "2", "1"]