Objective-C Calculating string value

夙愿已清 提交于 2019-12-11 03:21:26

问题


This is my main:

int x=0;
NSString *new=[[NSString alloc]initWithString:@"9+4"];
x=[new intValue];
NSLog(@"hi %i",x);

This results in 9.. .since giving the intValue of a string will read only numbers and stops when the character is not a digit.

So how can i print the result of my string and get a 13 instead??


回答1:


Change this line

NSString *new=[[NSString alloc]initWithString:@"9+4"];

to

NSString *new=[NSString stringWithFormat:@"%f",9+4];



回答2:


Actually, NSExpression was made just for this:

NSExpression *expression = [NSExpression expressionWithFormat:@"9+4"];
// result is a NSNumber
id result = [expression expressionValueWithObject:nil context:nil];

NSLog(@"%@", result);

NSExpression is very powerful, I suggest you read up on it. You can use variables by passing in objects through the format string.




回答3:


You will have to manually parse it. You could write a subclass of NSString that overrides the intValue method, and parses it to find arithmetic symbols and perform the math, but thats as close to automatic as you're gonna get I'm afraid




回答4:


You will need to parse and evaluate it yourself, as seemingly simple calculations like this are beyond the scope of the basic string parsing Apple provides you. It might seem to be a no-brainer if you're used to interpreted languages like Ruby, Perl and the like. But for a compiled language support for runtime evaluation of expressions are uncommon (there are languages that do support them, but Objective-C is not one of them).




回答5:


When attempting to parse an expression in a string you will want to use Reverse Polish Notation. Here is the first example I cam across in a google search for Objective-C.



来源:https://stackoverflow.com/questions/6072439/objective-c-calculating-string-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!