如何评估ios中的string方程
有没有办法解决在ios
的string方程?
例如
input:
NSString * str =@"1+2";
输出:
NSInteger result = 3
//即来自str
的1 + 2的总和
如何去做到这一点,并得到预期的结果!
请帮忙!
你可以使用NSExpression来达到这个目的:
NSExpression *expression = [NSExpression expressionWithFormat:@"1+2"]; NSLog(@"%@", [expression expressionValueWithObject:nil context:nil]);
有关更多信息,请阅读所用方法的文档。
如果你的mathexpression式足够简单,你可以按照Rajan Balana的build议去做手动路线。
要评估更复杂的expression式,可以使用/滥用NSPredicate
与NSExpression
相结合,如本博客中所述: http : NSExpression
请注意,只有当您的input是一个等式(包括正确的部分)时才需要NSPredicate
:
NSPredicate* parsedExpression = [NSPredicate predicateWithFormat:@"1+2=x"]; NSExpression* leftPart = [(NSComparisonPredicate*)parsedExpression leftExpression]; NSNumber* evaluatedResult = [leftPart expressionValueWithObject:nil context:nil]; NSLog(@"Expr:%@", evaluatedResult);
为了实现正确的parsing,您可以使用Objective-C的mathparsing器之一。 我自己并没有使用过,但stream行的似乎是
- GCMathParser
- DDMathParser
用这个 :
NSString * str =@"1+2"; NSArray *arr = [str componentsSeparatedByString:@"+"]; int sum = 0; for (int i = 0; i < [arr count]; i++) { sum += [[arr objectAtIndex:i] intValue]; } NSLog(@"sum : %d",sum);
输出:sum = 6
你也可以使用NSExpression 。
expression式是谓词实现的核心。 当调用expressionValueWithObject:时 ,将计算expression式,并返回一个可由操作员处理的值。 expression式可以是从常量到方法调用的任何东西。 标量应该包装在合适的NSValue类中。
例如:
NSLog(@"sum : %@", [[NSExpression expressionWithFormat:@"1+4"] expressionValueWithObject:nil context:nil]); Output :- sum : 5 NSLog(@"mulitple : %@", [[NSExpression expressionWithFormat:@"2*4"] expressionValueWithObject:nil context:nil]); Output :- mulitple : 8
希望它可以帮助你。
你可以做的是,你可以使用这个方法得到由符号“+”分隔的string的组件,然后你将得到组件的数组,即1,2。
NSArray* foo = [str componentsSeparatedByString: @"+"];
int result = [[foo objectAtIndex:0] integerValue] + [[foo objectAtIndex:1] integerValue];
然后您可以使用这两个元素的整数值并添加它们并将结果存储在一个整数variables中。
我认为你需要subString
你的string,并存储每个数字在一个新的NSstring
(integerValue)或Integer
variables。
例:
NSString *str = @"1+2"; int x = [[str substringToIndex:1]integerValue]; int y = [[str substringFromIndex:1]integerValue]; int z = x+y; NSLog(@"Sum === %d",z);
取决于你的inputstring方程的复杂性。 您可以使用Shunting-yardalgorithm来parsingmath方程,然后从Abstract Syntact Tree (AST)
计算方程,
但我希望你正在寻找一些容易,最好已经完成的解决scheme。 在这种情况下,你可以尝试其中的一个(不保证,我没有尝试过,只是google):