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)//67890
print(s2)//1234
print(s3)//5
// 扩展String
extension 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
原文链接:https://www.f2er.com/swift/323136.html