Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 447
Richard Birkett Avatar asked Apr 20 '16 14:04

Richard Birkett


People also ask

How to split characters of a string in Swift?

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.

How do I convert a string to an array in Swift?

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.


2 Answers

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"]

like image 121
Eric Aya Avatar answered Oct 13 '22 23:10

Eric Aya


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"]

like image 42
Casey Fleser Avatar answered Oct 13 '22 23:10

Casey Fleser