I just have this expression in an object with NSString: @ "10 + 5 * 2". I wanted to solve this expression automatically and came across a solution:
UIWebView *webView = [[UIWebView alloc] init]; NSString *result = [webView stringByEvaluatingJavaScriptFromString:expression]; NSLog(@"%@",result);
This works well, but it gives the result: 20. Actually, it evaluates "*" first means first 5 * 2 = 10 + 10. But I want to remove this priority and just want each operator to have the same priority from left to right, so that the answer can be equal to 10 + 5 = 15 * 2 = 30.
Although writing your own function is the last option, I really don't want to interfere with string functions. I would like to use something inline.
Thanks,
******* Working solution ********
Thank you for your help Eiko and Ozair !! Based on their answers, I wrote this bunch of code that works great for me!
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);
source share