字符串形式的数学表达式是否有现成的解析器?

时间:2012-09-10 13:14:27

标签: objective-c c parsing math

给出字符串:

"10 + 20 - 5 * 7 + (20 / 5)"

是否有任何可用的解析器可以对此进行评估,或者我是否需要编写自己的解析器?

1 个答案:

答案 0 :(得分:1)

this查看newacct帖子。

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"