Swift - 扩展 String 转换计算字符

简单扩展了下 String 支持转换四则运算的计算字符,若要加入更多支持,可以自己加入扩展。下面的扩展只是把字面上的字符串,简单转化成中缀表达式并且分割成了数组,方便转后缀表达式计算结果。
var str = "{1+2-[(1+2)x2]x2}"
str.ConverCalculateChar()
//str =["(","1","+","2","-","(","(","1","+","2",")","*","2",")","*","2",")"]




extension String {
 
    mutating func ConverCalculateChar() -> [String] {
        var console = true //控制合成连续数字字符
        var SerialNumber = ""
        var strArr = [String]()
        self += "A" //临时帮助下循环正常进行
        for  char in self.characters {
            switch char {
                case "0","1","2","3","4","5","6","7","8","9",".":
                    console == true ? (SerialNumber += String(char)) : (SerialNumber = String(char))
                console = true
            default:
               console = false
               if !SerialNumber.isEmpty {
                strArr.append(SerialNumber)
                SerialNumber = ""
                }
                strArr.append(String(char))
            }
        }
        strArr.removeLast() //删除刚刚的重要临时工"A"
        var index = 0
        for str in strArr {
            switch str {       //设定一定的容错性转换
                case "X", "x", "×":
                strArr[index] = "*"
                case "÷":
                strArr[index] = "/"
                case "(", "{", "[":
                strArr[index] = "("
                case ")", "}", "]":
                strArr[index] = ")"
            default:
                break
            }
           index += 1
        }
        return strArr
    }
}

你可能感兴趣的:(Swift - 扩展 String 转换计算字符)