Last active
January 31, 2016 03:46
-
-
Save getaaron/8f889dd9bb1cb479aef1 to your computer and use it in GitHub Desktop.
A Swift extension to split a string into an array of strings
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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