Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Perl style substring for Swift String
extension String {
/**
Perl style substring
- parameter offset: Negative offset starts that far back from the end of the string
- parameter length: Negative length leaves that many characters off the end of the string. Omit to return everything through the end of the string.
*/
func substr(offset: Int, length: Int = 0) -> String {
let start = offset < 0 ? endIndex.advancedBy(offset, limit: startIndex) : startIndex.advancedBy(offset, limit: endIndex)
let end = length > 0 ? start.advancedBy(length, limit: endIndex) : endIndex.advancedBy(length, limit: startIndex)
return substringWithRange(start ..< end)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.