小胖说swift05--------swift中字符串截取方法(substring)

前端之家收集整理的这篇文章主要介绍了小胖说swift05--------swift中字符串截取方法(substring)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
 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

猜你在找的Swift相关文章