45

In Swift, it's easy to split a string on a character and return the result in an array. What I'm wondering is if you can split a string by another string instead of just a single character, like so...

let inputString = "This123Is123A123Test"
let splits = inputString.split(onString:"123")
// splits == ["This", "Is", "A", "Test"]

I think NSString may have a way to do as much, and of course I could roll my own in a String extension, but I'm looking to see if Swift has something natively.

Mark A. Donohoe
  • 28,442
  • 25
  • 137
  • 286
  • 1
    @AhmadF, this is not a duplicate of splitting a string into an array. This is specifically splitting a string *on a string* instead of a character. As such, could you please remove the dup vote. Thanks! :) – Mark A. Donohoe Mar 25 '18 at 07:24
  • If you tried to `cmd` and click on `components(separatedBy: "123")`, you would note that the type of the `separator` parameter is [StringProtocol](https://developer.apple.com/documentation/swift/stringprotocol) which means that it could take a single character or a string :) – Ahmad F Mar 25 '18 at 07:31
  • Yes, but I wasn't looking at that. I was looking at the 'split' function which doesn't have that option, hence my question and it's specific request. I saw that other question before posting this but disregarded it because that specifically asked about a character whereas I needed a string delimiter. Again, this ***question*** is not a duplicate even if the answer is the same, just as you can use a coffee cup for both coffee and hot chocolate. Same cup. Different reason for using it. Again, please remove the dup vote. Thanks! – Mark A. Donohoe Mar 25 '18 at 07:34

2 Answers2

75
import Foundation

let inputString = "This123Is123A123Test"
let splits = inputString.components(separatedBy: "123")
Gi0R
  • 1,387
  • 2
  • 13
  • 15
-1

You mean this?

let developer = "XCode Swift"
let array = developer.characters.split{" "}.map(String.init)

array[0] // XCode
array[1] // Swift
luistejadaa
  • 89
  • 11