Swift: How to get substring from start to last index of character

前端 未结 22 858
感情败类
感情败类 2020-11-30 19:09

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.

22条回答
  •  难免孤独
    2020-11-30 20:06

    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"
    

提交回复
热议问题