汉字转阿拉伯数字

自取:

extension String{
    func ChineseToNum()->String{
        
        guard characters.count > 0 else { return "" }
        guard (["百","千","万","千万"].filter{ $0 == self }.count == 0) else { return "" }
        
        let numString = ["零","一","二","三","四","五","六","七","八","九"]
        
        let handle = { (resource:String) -> String in
            switch resource {
            case "十":return "0"
            case "百":return "00"
            case "千":return "000"
            case "万":return "0000"
            default :return ""
            }
        }
        
        let loop = { (resource:String,isSpecial:Bool) -> String in
            return resource.characters.enumerated().reduce(""){
                let temp = "\(numString.index(of: String($1.element)) ?? -1)"
                let placeholder = isSpecial ? handle(String($1.element)) : ""
                return $0 + (temp == "-1" ? placeholder : temp)
            }
        }
        
        let normal = { (resource:String) -> String in
            let result = loop(resource,false) + handle(String(describing: resource.characters.last))
            return resource.characters.count == 2 && String(resource.characters[resource.startIndex]) == "十" ? "1" + result : result
        }
        
        if contains("零"){
            let intermediate = components(separatedBy: "零")
            return "\((Int(loop(intermediate[0],true)) ?? 0) + (Int(normal(intermediate[1])) ?? 0))"
        }
        else{
            return normal(self)
        }
    }
}

你可能感兴趣的:(汉字转阿拉伯数字)