From 577dc7fe64c3c79fea7ea66c55df85dee00c4577 Mon Sep 17 00:00:00 2001 From: oisdk Date: Wed, 27 May 2015 00:16:50 +0100 Subject: [PATCH] Splitting for Strings --- ExSwift/String.swift | 61 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) 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)}) + } }