Simple math expression solve in objective c from left to right
I simply have this expression in objective c NSString: @"10+5*2". I wanted to solve this expression automatically and came across to a solution:
UIWebView *webView = [[UIWebView alloc] init];
NSString *result = [webView stringByEvaluatingJavaScriptFromString:expression];
NSLog(@"%@",result);
The above works well but it produces a result: 20. Actually this evaluates the "*" first means first it does 5*2 = 10 + 10. But I want to remove this precedence and simply wants each operator having same precedence with left to right so that answer could be 10+5 = 15 * 2 = 30.
Although writing own function is the last option but I really don't want to mess-up with the string functions. I would like to use something built in.
Thanks,
******* Working solution ********
Thanks for all your help Eiko and Ozair!! Based on their answers I have written this bunch of code which works perfectly 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++;
开发者_StackOverflow社区 }
}
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);
Not sure if it's the same as @Ozair Kafray says...
For each operator that you append to the string, add a )
first and add the matching (
at the beginning. I.e.
10
(10 ) +
(10 ) + 5
((10 ) + 5 ) *
((10 ) + 5 ) * 2
Just make sure that when deleting an operator to also delete the parentheses as well.
No built in way to do this that I know of. I think you will just have to roll up your sleeves and write a function. If you want to use objective-c then use NSScanner.
As from your answer to my question in comments, you are generating the string during input. I would suggest that you add a parenthesis after every operand except the first one.
So you do not add anything to string after 10
, then the operator +
is added. After that for each operand that is 5
add a closing parenthesis )
and a corresponding opening parenthesis (
to the start of string. Similarly after 2
. This way you won't have to write anything of your own for processing the string.
精彩评论