NSExpresseion,从左结合判断操作

NSExpresseion, determine operating from left-associative

func postFix(_ expr: String) -> Int {
    // write your code here
    let nums = expr.components(separatedBy:CharacterSet.decimalDigits.inverted)
        .joined()
    let set = CharacterSet(charactersIn: "+*/%-")
    var ch = expr.components(separatedBy: set.inverted).joined()
    ch.append(" ")
    var rslt = String()


    for i in 0..<nums.count {
        let index = str.index(str.startIndex, offsetBy: i)
        rslt.append(nums[index])
        rslt.append(ch[index])
    }
    let theSet = CharacterSet(charactersIn: "+*/%-0123456789")
    let final = rslt.components(separatedBy: theSet.inverted).joined()
    let expn = NSExpression(format: final)
    let chal = expn.expressionValue(with: nil, context: nil)

    return  chal as! Int
}
print(postFix("4 1 - 2 *"))

我正在制作一种方法来从未排序的字符串中解析数学运算 我面临的唯一问题是我无法确定从 left-associative 操作。 而不是 4 - (1 * 2) = 2 我希望它从左侧开始并忽略是否先以 * 或 / 开始 所以 (4 - 1 ) * 2 = 6

我会稍微改变一下你的逻辑。首先获取所有数字和所有运算符,然后获取第一个元素并将其用作 lhs,迭代数字和运算符删除第一个数字。使用 lhs + 运算符 + 当前数字 (rhs) 构造表达式。将结果分配给 var,下一个 lhs 将是转换为字符串的结果。类似于:


func postFix(_ expr: String) -> Int {
    let numbers = expr.split(whereSeparator: {!"0123456789".contains([=10=])})
    let operators = expr.split(whereSeparator: {!"+*/%-".contains([=10=])} )
    guard var lhs = numbers.first else { return .zero }
    var result = 0
    for (rhs, oprtr) in zip(numbers.dropFirst(),operators)  {
        let format = String([lhs,rhs].joined(separator: " " + oprtr + " "))
        result = NSExpression(format: format)
            .expressionValue(with: nil, context: nil) as? Int ?? 0
        lhs = String(result)[...]
    }
    return  result
}

print(postFix("4 1 - 2 *"))  // "6\n"