Skip to content
This repository was archived by the owner on Mar 29, 2018. It is now read-only.

Splitting for Strings #122

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 61 additions & 0 deletions ExSwift/String.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)})
}

}

Expand Down