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)