String interception method in Swift (substring)

Source: Internet
Author: User

Here are the 2 types of Swift string interception methods that are actually used substringFromIndex , substringToIndexsubstringWithRange

1. will be String converted to NSString re-interception, the code is as follows:

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. The corresponding method of direct invocation String (this method is recommended), because String the corresponding method parameter is a type String.Index rather than a Int type, so we first create String.Index the type parameter value, the code is as follows:

var s= "1234567890" Let index = Advance (S.startindex, 5) Let Index2 = Advance (S.endindex,-6); var range = Range<string.ind Ex> (Start:index2,end:index) var s1:string=s.substringfromindex (index) var s2:string=s.substringtoindex (INDEX2) var s3=s.substringwithrange (range) println (S1)//67890println (S2)//1234println (S3)//5

By String definition, you can see that Index a property is a struct, with the following code:

Extension String:collectiontype {struct index:bidirectionalindextype, comparable, reflectable {func succes  Sor (), String.index func predecessor (), String.index func getmirror (), Mirrortype} var StartIndex:String.Index {get} var endIndex:String.Index {get} subscript (I:string.index), Character {g ET} func Generate ()-indexinggenerator<string>}


String interception method in Swift (substring)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.