1

I have a mathematical equation in string format.

Is there a way to convert @"+"(String constant) directly to addition operator in objective C Or

I have to use If-Else statements to solve this equation ??

  • What's the particular use case that you're inquiring about this for? Ie why do you want to do this? – Alfie Hanssen Jul 29 '13 at 17:16
  • 123+456+678-985 it is in the form of a string constant. can I convert it into mathematical equation like (float I=123+456+678-985) – DemonicPossessions1991 Jul 29 '13 at 17:21
  • If it's just @"+" just compare strings. If you actually want to evaluate expressions, then I suggest look for an open source implementation of string equations. – 0xSina Jul 29 '13 at 17:22
  • yes, of course. comparing with IF-ELSE work fine, but I wasn't worried about that. I just wanted to know if there is a way to convert this directly..:) – DemonicPossessions1991 Jul 29 '13 at 17:26

3 Answers3

3
NSPredicate * parsed = [NSPredicate predicateWithFormat:@"123+456+678-985 = 0"];
NSExpression * left = [(NSComparisonPredicate *)parsed leftExpression];
NSNumber * result = [left expressionValueWithObject:nil context:nil];
float i = [result floatValue];
0xSina
  • 20,973
  • 34
  • 136
  • 253
  • 1
    You don't need the predicate, compare http://stackoverflow.com/questions/12500232/i-have-formula-in-a-nsstring-how-to-evaluate-it/12500518#12500518. – Martin R Jul 29 '13 at 17:38
0
if([yourString isEqualToString:@"+"])
{
     //Do something

}

This code should work.

Abdullah Shafique
  • 6,878
  • 8
  • 35
  • 70
0

You can use NSExpression to achieve this

NSString *expressionFormat = [NSString stringWithFormat:@"(%d %@ %d)",firstNumber,arcthimaticOperator,secondNumber];
NSExpression *expression = [NSExpression expressionWithFormat:expressionFormat];
NSNumber *result = [expression expressionValueWithObject:nil context:nil];
NSLog(@"%@", result);

Please make sure you enter the correct format else the above code will throw exception.

Bug Hunter Zoro
  • 1,743
  • 18
  • 21