6

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

2 Answers 2

7

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. So are we saying that there is no Swift solution, only Obj-C ones?
This is brilliant!
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"]

2 Comments

By copying and pasting your first code directly I got ["0", " 1", " 2", " 1"] which is half the problem I have, Swift hates spaces.
Ah yeah you're right. My bad. You can either run each through stringByTrimmingCharactersInSet or add a space to the NSCharacterSet. I'll edit my answer to reflect that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.