我在objective c中有这个表达式NSString: @"10+5*2"。 我希望自动解决这个表达式,然后发现了一个解决方案:
UIWebView *webView = [[UIWebView alloc] init];
NSString *result = [webView stringByEvaluatingJavaScriptFromString:expression];
NSLog(@"%@",result);
上述方法很好,但会产生结果:20。实际上,这个表达式首先计算 "*",即 5*2 = 10 + 10。但我想消除这种优先级,使每个运算符从左到右具有相同的优先级,以便答案为 10+5 = 15 * 2 = 30。
虽然编写自己的函数是最后的选择,但我真的不想搞乱字符串函数。我想使用一些内置的东西。
谢谢,
**工作解决方案**
感谢 Eiko 和 Ozair 的所有帮助!根据他们的答案,我编写了这一堆代码,对我来说完美无缺!
NSString *expression = lblBox.text; // Loads the original expression from label.
expression = [expression stringByReplacingOccurrencesOfString:@"+" withString:@")+"];
expression = [expression stringByReplacingOccurrencesOfString:@"-" withString:@")-"];
expression = [expression stringByReplacingOccurrencesOfString:@"*" withString:@")*"];
expression = [expression stringByReplacingOccurrencesOfString:@"/" withString:@")/"];
NSUInteger count = 0, length = [expression length];
NSRange range = NSMakeRange(0, length);
while(range.location != NSNotFound)
{
range = [expression rangeOfString: @")" options:0 range:range];
if(range.location != NSNotFound)
{
range = NSMakeRange(range.location + range.length, length - (range.location + range.length));
count++;
}
}
for (int i=0; i<count; i++) {
expression = [@"(" stringByAppendingString:expression];
}
UIWebView *webView = [[UIWebView alloc] init];
NSString *result = [webView stringByEvaluatingJavaScriptFromString:expression];
[webView release];
NSLog(@"%@ = %@",expression, result);