Skip to content

Instantly share code, notes, and snippets.

@getaaron
Last active January 31, 2016 03:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save getaaron/8f889dd9bb1cb479aef1 to your computer and use it in GitHub Desktop.
Save getaaron/8f889dd9bb1cb479aef1 to your computer and use it in GitHub Desktop.
A Swift extension to split a string into an array of strings
extension String {
func split(string: String) -> [String] {
guard !string.characters.isEmpty else { return [string] }
var strings: [String] = []
let targetDistance = string.characters.startIndex.distanceTo(string.characters.endIndex)
var currentIndex = self.startIndex
var currentView = String.CharacterView()
while currentIndex < self.endIndex {
let tmpEndIndex = currentIndex.advancedBy(targetDistance, limit: self.endIndex)
if string == String(self[currentIndex..<tmpEndIndex]) {
if !currentView.isEmpty {
strings += [String(currentView)]
}
currentView = String.CharacterView()
currentIndex = currentIndex.advancedBy(targetDistance)
} else {
currentView.append(self[currentIndex])
currentIndex = currentIndex.advancedBy(1)
}
}
if !currentView.isEmpty {
strings += [String(currentView)]
}
return strings
}
}
let source = "WUBWEWUBAREWUBWUBTHEWUBCHAMPIONSWUBMYWUBFRIENDWUB"
let answer = source.split("WUB").joinWithSeparator(" ") // "WE ARE THE CHAMPIONS MY FRIEND"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment