swift中字串截取方法(substring)

來源:互聯網
上載者:User

下面介紹2種swift的字串截取方法,實際上用到了substringFromIndex,substringToIndex,substringWithRange

1.將String轉化為NSString再截取,代碼如下:

 var s="1234567890"var ns1=(s as NSString).substringFromIndex(5)var ns2=(s as NSString).substringToIndex(4)var ns3=(s as NSString).substringWithRange(NSMakeRange(4, 1))println(ns1)//67890println(ns2)//1234println(ns3)//5

2.直接調用String的對應方法(推薦使用該方法),由於String對應的方法參數是String.Index類型而非Int類型,所以我們首先要建立String.Index型別參數值,代碼如下:

// var s="1234567890"// let index = advance(s.startIndex, 5)  swift 1.x//let index2 = advance(s.endIndex, -6); swift 1.x var s="1234567890"let index = s.startIndex.advancedBy(5) //swift 2.0+let index2 = s.endIndex.advancedBy(-6) //swift 2.0+var range = Range<String.Index>(start: index2,end: index)var s1:String=s.substringFromIndex(index)var s2:String=s.substringToIndex(index2)var s3=s.substringWithRange(range)print(s1)//67890print(s2)//1234print(s3)//5 // 擴充Stringextension String {    subscript (r: Range<Int>) -> String {        get {            let startIndex = self.startIndex.advancedBy(r.startIndex)            let endIndex = self.startIndex.advancedBy(r.endIndex)            return self[Range(start: startIndex, end: endIndex)]        }    }}var s4 = s[2...4]print(s4);//345

通過String定義可以看出屬性Index是個結構體,具體代碼如下:

extension String : CollectionType {    struct Index : BidirectionalIndexType, Comparable, Reflectable {        func successor() -> String.Index        func predecessor() -> String.Index        func getMirror() -> MirrorType    }    var startIndex: String.Index { get }    var endIndex: String.Index { get }    subscript (i: String.Index) -> Character { get }    func generate() -> IndexingGenerator<String>}

相關文章

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.