swift中字符串截取方法(substring)

下面介绍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)//67890
println(ns2)//1234
println(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)//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

通过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>
}
阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页