I want to learn the best/simplest way to turn a string into another string but with only a subset, starting at the beginning and going to the last index of a character.
I also build a simple String-extension for Swift 4:
extension String {
func subStr(s: Int, l: Int) -> String { //s=start, l=lenth
let r = Range(NSRange(location: s, length: l))!
let fromIndex = self.index(self.startIndex, offsetBy: r.lowerBound)
let toIndex = self.index(self.startIndex, offsetBy: r.upperBound)
let indexRange = Range(uncheckedBounds: (lower: fromIndex, upper: toIndex))
return String(self[indexRange])
}
}
So you can easily call it like this:
"Hallo world".subStr(s: 1, l: 3) //prints --> "all"