diff --git a/ExSwift/String.swift b/ExSwift/String.swift index 2c7f1b6..ed656cf 100644 --- a/ExSwift/String.swift +++ b/ExSwift/String.swift @@ -291,6 +291,67 @@ public extension String { func toDateTime(format : String? = "yyyy-MM-dd hh-mm-ss") -> NSDate? { return toDate(format: format) } + + /** + Splits a string at a given index + + :param: ind The index at which to split the string + :returns: An array with two elements: the first and second part of the string + */ + + func split(ind: String.Index) -> [String] { + return [self.substringToIndex(ind), self.substringFromIndex(ind)] + } + + /** + Splits a string at given indices + + :param: inds an array of indices at which to split the string + :returns: An array of the split strings + */ + + func split(inds: [String.Index]) -> [String] { + return multiSplit(sorted(inds)) + } + + /** + Recursive helper function for splitting a string at several indices + */ + + private func multiSplit(var inds: [String.Index]) -> [String] { + + if inds.isEmpty { return [self] } else { + + let ind = inds.removeLast() + + return self.substringToIndex(ind) + .multiSplit(inds) + + [self.substringFromIndex(ind)] + + } + } + + /** + Splits a string at a given index + + :param: ind The index at which to split the string + :returns: An array with two elements: the first and second part of the string + */ + + func split(ind: Int) -> [String] { + return split(advance(self.startIndex, ind)) + } + + /** + Splits a string at given indices + + :param: inds an array of indices at which to split the string + :returns: An array of the split strings + */ + + func split(inds: [Int]) -> [String] { + return split(inds.map{advance(self.startIndex, $0)}) + } }