[英]Convert String to operator - swift
I have many variations of String equations in my program. 我的程序中有很多String方程式。
" 1 + 9 X 8" “ 1 + 9 X 8”
" 4 + 6" “ 4 + 6”
" 5 / 9 + 7" “ 5/9 + 7”
" 3 X 8" “ 3 X 8”
So, what I want to do is to perform the calculation and give the result. 所以,我要做的是执行计算并给出结果。 However, I am not able to figure out a way to read the operator characters ("+ / X +") and fit it to the equation.
但是,我无法找到一种读取运算符(“ + / X +”)并将其拟合等式的方法。 Hope my question is clear.
希望我的问题清楚。
Note: I am able to read the digit characters, which is simple a String to Int conversion. 注意:我能够读取数字字符,这很简单,就是从String到Int的转换。 But, I am having difficulties converting the String equivalent of the characters (" X / + -") to its operators.
但是,我很难将等效于字符的字符串(“ X / +-”)转换为其运算符。 How can I do this ?
我怎样才能做到这一点 ?
If this is not possible, can someone suggest a workaround. 如果这不可能,那么有人可以建议解决方法。
try something like this 尝试这样的事情
var s = " 1 + 9 X 8"
s = s.replacingOccurrences(of: "X", with: "*")
let expn = NSExpression(format:s)
print("\(expn.expressionValue(with: nil, context: nil) ?? 0)")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.