swift4 字符串截取

2018-10-16  本文已影响0人  誓言_acaa
extension String {
    func mySubString(to index: Int) -> String {
        return String(self[..<self.index(self.startIndex, offsetBy: index)])
    }
    
    func mySubString(from index: Int) -> String {
        return String(self[self.index(self.startIndex, offsetBy: index)...])
    }
    
    func mySubString(start index: Int,end index1: Int) -> String {
        let start = self.index(self.startIndex, offsetBy: index)
        let end = self.index(self.startIndex, offsetBy: index1)
        let range = Range<String.Index>(uncheckedBounds: (lower: start, upper: end))
        return String(self[range])
    }

使用

let test = "0123456789"
print(test.mySubString(to: 3))
print(test.mySubString(from: 5))
print(test.mySubString(start: 1, end: 5))

结果
012
56789
1234

上一篇下一篇

猜你喜欢

热点阅读