Swift字符处理

2018-10-07  本文已影响0人  DavidWongDev

比起很多传统语言,Swift在字符处理方面显得更加简洁易用。本文会总结一些Swift在字符处理上的常用方法,持续更新中。
环境:Mac+Swift4

十进制,二进制,和十六进制的转化

    class func simple(){
        //十进制转二进制
        let dec = 15
        let bin = String.init(dec, radix: 2, uppercase: true)
        print("decimal \(dec) transfer to bin \(bin)")
        
        //二进制转十进制
        let descNew = Int(bin, radix: 2) ?? 0
        print("bin \(bin) transfer to decimal \(descNew)")
        
        //十进制转十六进制
        let hex = String.init(dec, radix: 16, uppercase: true)
        print("decimal \(dec) transfer to hex \(hex)")
        
        //十六进制转十进制
        let descNew2 = Int(hex,radix:16) ?? 0
        print("hex \(hex) transfer to decimal \(descNew2)")
    }

这里补充记录一下字符相关基础知识:

Swift4中字符遍历

用一个例子说明
我们将一个A10B1C2的解压为AAAAAAAAAABCC

    class func unZip(){
        let origial = "A10B1C2"
        var result = ""
        var tempNumber = 0
        var tempStr = ""
        let size = origial.count
        for (index,c) in Array(origial).enumerated() {
            let s = String(c)
            if(s.isInt){
                if(index==(size-1)){
                   tempNumber = tempNumber*10 + (Int(s) ?? 0)
                   result = result + unzipSingleWord(word: tempStr, num: tempNumber)
                }
                else{
                    tempNumber = tempNumber*10 + (Int(s) ?? 0)
                }
            }
            else{
                result = result + unzipSingleWord(word: tempStr, num: tempNumber)
                tempStr = s
                tempNumber = 0
            }
        }
        print("result is \(result)")
    }

其中,对String是数字还是普通字符我们可以这样判断

extension String {
    var isInt: Bool {
        return Int(self) != nil
    }
}
上一篇下一篇

猜你喜欢

热点阅读