Richard Birkett Richard Birkett - 7 months ago 30
Swift Question

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)?

Answer

You could use .stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) to remove the spaces:

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

Gives:

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