开发者

Objective-C Calculating string value

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??


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.


Change this line

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

to

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


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


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).


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜