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)?
To split a String by Character separator in Swift, use String. split() function. Call split() function on the String and pass the separator (character) as argument. split() function returns a String Array with the splits as elements.
To convert a string to an array, we can use the Array() intializer syntax in Swift. Here is an example, that splits the following string into an array of individual characters. Similarly, we can also use the map() function to convert it. The map() function iterates each character in a string.
Swift 3
let s = "[0, 1, 2, 1]"
let splitted = s.characters.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"]
A couple of possibilities spring to mind. If you can use characters as separators:
let str = "[0, 1, 2, 1]"
let separatorSet = NSCharacterSet(charactersInString: ",[]")
let comps = str.componentsSeparatedByCharactersInSet(separatorSet).filter({return !$0.isEmpty})
This yields
["0", " 1", " 2", "1"]
If necessary, the spaces can be removed by either mapping with stringByTrimmingCharactersInSet
or by adding a space to the separatorSet
.
Or if you really need to use strings as separators:
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})
}
Which yields:
["0", "1", "2", "1"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With