2

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

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
Dani
  • 1,228
  • 1
  • 16
  • 26
  • If you're looking for the same thing I was looking for a time ago, check out the accepted answer to my question regarding the same topic, helped me a lot and worked perfectly: http://stackoverflow.com/questions/4969618/execute-a-prepared-math-operation-in-objective-c – Björn Kaiser Jan 15 '12 at 14:46

5 Answers5

8

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.

Richard J. Ross III
  • 55,009
  • 24
  • 135
  • 201
0

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

Dan F
  • 17,654
  • 5
  • 72
  • 110
0

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

DarkDust
  • 90,870
  • 19
  • 190
  • 224
0

Change this line

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

to

NSString *new=[NSString stringWithFormat:@"%f",9+4];
Richard J. Ross III
  • 55,009
  • 24
  • 135
  • 201
John Ballinger
  • 7,380
  • 5
  • 41
  • 51
  • First, I'm pretty sure the string is just an example and the input is unexpected. Second, I'd use the `%d` or `%u` sequence, `%f` is for floating point. – DarkDust May 20 '11 at 13:21
  • Ha, thats what he wanted all along :) – Joe May 20 '11 at 14:49
0

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.

Joe
  • 56,979
  • 9
  • 128
  • 135