Skip to content

Instantly share code, notes, and snippets.

@pyrtsa
Created October 4, 2014 13:45
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pyrtsa/c6af49d8f2d95a6b454d to your computer and use it in GitHub Desktop.
Save pyrtsa/c6af49d8f2d95a6b454d to your computer and use it in GitHub Desktop.
Splitting strings by a separator string in Swift
import Foundation
extension String {
public func split(separator: String) -> [String] {
if separator.isEmpty {
return map(self) { String($0) }
}
if var pre = self.rangeOfString(separator) {
var parts = [self.substringToIndex(pre.startIndex)]
while let rng = self.rangeOfString(separator, range: pre.endIndex..<endIndex) {
parts.append(self.substringWithRange(pre.endIndex..<rng.startIndex))
pre = rng
}
parts.append(self.substringWithRange(pre.endIndex..<endIndex))
return parts
} else {
return [self]
}
}
}
// Examples:
"".split(", ") //=> [""]
"a".split(", ") //=> ["a"]
"a, b, c, def".split(", ") //=> ["a", "b", "c", "def"]
"foobar".split("o") //=> ["f", "", "bar"]
"foo".split("foo") //=> ["", ""]
// Special case: splitting by empty separator gets the list of glyphs as Strings
"".split("") //=> [], notably different from "".split(s) with any other separator s
"a".split("") //=> ["a"]
"abcd".split("") //=> ["a", "b", "c", "d"]
"O\u{305}saka".split("") //=> ["O̅", "s", "a", "k", "a"], works with combining diacriticals
@pyrtsa
Copy link
Author

pyrtsa commented Oct 4, 2014

Interestingly, rangeOfString needs Foundation imported. The String struct is clearly still missing a lot of useful members in the standard library.

@AstroCB
Copy link

AstroCB commented Feb 11, 2015

This seems to cause a runtime error with Swift 1.2 in Xcode 6.3 beta 1 on line 12, but I'm not sure why.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment