给出字符串:
"10 + 20 - 5 * 7 + (20 / 5)"
是否有任何可用的解析器可以对此进行评估,或者我是否需要编写自己的解析器?
答案 0 :(得分:1)
NSString *equation = @"10 + 20 - 5 * 7 + (20 / 5)";
// dummy predicate that contains our expression
NSPredicate *pred = [NSPredicate predicateWithFormat:
[equation stringByAppendingString:@" == 42"]];//42 is just a rightExpression to make it an equation
NSExpression *exp = [pred leftExpression];
NSNumber *result = [(NSComparisonPredicate *)exp expressionValueWithObject:nil context:nil];
NSLog(@"%@", result); // logs "-1"