Search code examples
iosobjective-cios5nsstringnsinteger

How to evaluate the string equation in ios


Is there way to solve the string equations in ios ?

For example

Input:

NSString * str =@"1+2";

Output:

NSInteger result = 3 // i.e sum of 1+2 from str

How to go about this and get expected result!

Please help!


Solution

  • You can use NSExpression for this:

    NSExpression *expression = [NSExpression expressionWithFormat:@"1+2"];
    NSLog(@"%@", [expression expressionValueWithObject:nil context:nil]);
    

    For further information read the documentation of the used methods.