将带有数学表达式的字符串转换为float

时间:2011-07-24 21:40:54

标签: objective-c cocoa math expression string-parsing

文本字段包含以下数学表达式:12+45-6是否可以将此字符串转换为数字?

我们可以使用谓词工具吗?

NSString *foo = @"((a*b)/c+(d/5))+15";
// dummy predicate that contains our expression
NSPredicate *pred = [NSPredicate predicateWithFormat:[foo stringByAppendingString:@" == 42"]];
NSExpression *exp = [pred leftExpression];
NSNumber *result = [exp expressionValueWithObject:[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:4], @"a",[NSNumber numberWithInt:7], @"b",[NSNumber numberWithInt:2], @"c",[NSNumber numberWithInt:20], @"d",nil]context:nil];
NSLog(@"%@", result); // logs "33"<br/>

我也发现了https://github.com/unixpickle/ANExpressionParser

4 个答案:

答案 0 :(得分:2)

一个不依赖于外部库的解决方案是首先将字符串转换为一系列标记,然后使用链接到简单堆栈计算机上的shunting-yard algorithm来计算表达式。

答案 1 :(得分:1)

您需要使用解析器解析此输入,然后对其进行评估。我听说有人成功使用muParser来节省你自己写的全部内容。看看这个。 http://muparser.sourceforge.net/

答案 2 :(得分:0)

是。阅读“表达式评估”,或使用现成的脚本解释器。作为WebView的一部分,JavaScript可用于所有iOS程序。

答案 3 :(得分:0)

是的,当然有可能。

您应该使用堆栈查看中缀到后缀转换:http://scriptasylum.com/tutorials/infix_postfix/algorithms/infix-postfix/index.htm

然后研究如何使用堆栈评估postix表达式:http://scriptasylum.com/tutorials/infix_postfix/algorithms/postfix-evaluation/index.htm

相关问题