[Swift 3.0]String的Extension--字串的截取

來源:互聯網
上載者:User

在Swift中進行字串的截取的時候, 不像使用NSString那麼方便, 這是因為String的截取方法substring(from: <#T##String.Index#>)所需要的參數不是Int類型, 這在使用的時候就很不方便, 這裡我對String寫了一個Extension, 用法十分簡單:

extension String {    // 字串的第一個字元    var first: String {        return self.substringTo(0)    }    // 字串的最後一個字元    var last: String {        return self.substringFrom(self.characters.count - 1)    }    // 字串開始到第index    func substringTo(_ index: Int) -> String {        guard index < self.characters.count else {            assertionFailure("index beyound the length of the string")            return ""        }        let theIndex = self.index(self.startIndex, offsetBy: index + 1)        return self.substring(to: theIndex)    }    // 從第index個開始到結尾的字元    func substringFrom(_ index: Int) -> String {        guard index < self.characters.count else {            assertionFailure("index beyound the length of the string")            return ""        }        guard index >= 0 else {            assertionFailure("index can't be lower than 0")            return ""        }        let theIndex = self.index(self.endIndex, offsetBy: index - self.characters.count)        return self.substring(from: theIndex)    }    // 某個閉區間內的字元    func substringInRange(_ range: CountableClosedRange<Int>) -> String {        guard range.lowerBound >= 0 else {            assertionFailure("lowerBound of the Range can't be lower than 0")            return ""        }        guard range.upperBound < self.characters.count else {            assertionFailure("upperBound of the Range beyound the length of the string")            return ""        }        let start = self.index(self.startIndex, offsetBy: range.lowerBound)        let end = self.index(self.startIndex, offsetBy: range.upperBound + 1)        let strRange = Range.init(uncheckedBounds: (lower: start, upper: end))        return self.substring(with: strRange)    }}

使用:

let str = "我愛寫BUG,寫BUG使我快樂"        print("前部分字元: \(str.substringTo(3))")        print("後部分字元: \(str.substringFrom(11))")        print("地區: \(str.substringInRange(10...13))")        print("第一個字串: \(str.first)")        print("最好一個字元: \(str.last)")

輸出:

前部分字元: 我愛寫B後部分字元: 使我快樂地區: G使我快第一個字串: 我最好一個字元: 樂

是不是很簡單呢?

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.