Search code examples
arraysstringswiftsplitseparator

Split String with more than one character in Swift


I've read the other threads but they only seem to deal with single character delimiters, and I think Playground is crashing for me because I use more than one char.

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

kinda works but I want to use " ," not ",". Obviously I can use [",", " ", "[", "]"] and that throws out the spaces but what about when I want only string patterns to be removed?

In brief: How do I separate a Swift string by precisely other smaller string(s)?


Solution

  • Swift 5

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

    Swift 2

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

    Result is an array of Strings without the extra spaces:

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