Swift3 String 一些操作

        title = "aaaaaa"
        //获取字符串的子串
        let s = "abcdefg"
        var s2  = s.substring(from: s.index(s.startIndex,offsetBy: 3))
        print("s2 = \(s2)")
        
        //这里只能使用..< 范围操作符,而不能使用...
        let range = s.index(s.startIndex,offsetBy: 3) ..< s.index(s.startIndex,offsetBy: 6)
        print("range = \(range)")
        
        s2 = s.substring(with: range)
        print("s2 = \(s2)")
        
        
        
        //搜索指定子串
        let index = s.range(of: "def")?.lowerBound
        if let idx = index {
            let postion = s.distance(from: s.startIndex, to: idx)
            print("postion is:\(postion)")
        }else{
            print("String not found");
        }
        
        
        
        struct TestStruct { var a: Int32 = 0; var b: Double = 0.0 }
        let obj = TestStruct()
        // 获取一个对象的大小
        let size = MemoryLayout.size(ofValue: obj)
        // 获取一个对象起始地址的字节对齐大小
        let align = MemoryLayout.alignment(ofValue: obj)
        // 获取一个对象倘若放在一个数组中,那么相邻两个元素之间的字节数(跨度)
        let stride = MemoryLayout.stride(ofValue: obj)
        
        print("size of obj: \(size)")           // 16
        print("alignment of obj: \(align)")     // 8
        print("stride of obj: \(stride)")       // 16

结果

Swift3 String 一些操作_第1张图片
屏幕快照 2016-12-19 下午2.40.01.png

你可能感兴趣的:(Swift3 String 一些操作)