Mark A. Donohoe
Mark A. Donohoe

Reputation: 30478

In Swift, can you split a string by another string, not just a character?

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.

Upvotes: 48

Views: 28192

Answers (2)

luistejadaa
luistejadaa

Reputation: 89

You mean this?

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

array[0] // XCode
array[1] // Swift

Upvotes: -1

Gi0R
Gi0R

Reputation: 1457

import Foundation

let inputString = "This123Is123A123Test"
let splits = inputString.components(separatedBy: "123")

Upvotes: 79

Related Questions