How to evaluate the string equation in ios
Asked Answered
I

6

18

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!

Imprecision answered 28/5, 2013 at 7:11 Comment(0)
A
32

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.

Anode answered 28/5, 2013 at 7:16 Comment(1)
+1 This is correct. You don't need something like my DDMathParser unless you need much more flexibility in the parsing/evaluation process.Nutwood
P
4

If your mathematical expressions are simple enough, you could go the manual route as suggested by Rajan Balana.

To evaluate more complex expressions, you could use/abuse NSPredicate in combination with NSExpression as described in this Blog post:http://funwithobjc.tumblr.com/post/1553469975/abusing-nspredicate

Note that NSPredicate is only necessary if your input is really an equation (including the right part):

NSPredicate* parsedExpression = [NSPredicate predicateWithFormat:@"1+2=x"];
NSExpression* leftPart = [(NSComparisonPredicate*)parsedExpression leftExpression];
NSNumber* evaluatedResult = [leftPart expressionValueWithObject:nil context:nil];
NSLog(@"Expr:%@", evaluatedResult);

To achieve proper parsing, you can use one of the math parsers for Objective-C out there. I haven't used them myself, but the popular ones seem to be

Pantywaist answered 28/5, 2013 at 7:18 Comment(0)
R
1

Use this :

NSString * str =@"1+2";

NSArray *arr = [str componentsSeparatedByString:@"+"];
int sum = 0;
for (int i = 0; i < [arr count]; i++) {
    sum += [[arr objectAtIndex:i] intValue];
}
NSLog(@"sum : %d",sum); 

Output : sum = 6

You can use NSExpression also.

Expressions are the core of the predicate implementation. When expressionValueWithObject: is called, the expression is evaluated, and a value returned which can then be handled by an operator. Expressions can be anything from constants to method invocations. Scalars should be wrapped in appropriate NSValue classes.

Example :

    NSLog(@"sum : %@", [[NSExpression expressionWithFormat:@"1+4"] expressionValueWithObject:nil context:nil]);
Output :- sum : 5
    NSLog(@"mulitple : %@", [[NSExpression expressionWithFormat:@"2*4"] expressionValueWithObject:nil context:nil]);
Output :- mulitple : 8

Hope it helps you.

Recitativo answered 28/5, 2013 at 7:17 Comment(0)
A
0

What you can do is, You can get the components of the string separated by the sign "+" using this method and then you will get the array of components i.e. 1,2.

NSArray* foo = [str componentsSeparatedByString: @"+"];

int result = [[foo objectAtIndex:0] integerValue] + [[foo objectAtIndex:1] integerValue];

and then you can use the integer value for those two elements and add them and store the result in an integer variable.

Ariannearianrhod answered 28/5, 2013 at 7:14 Comment(6)
what you will do if * instead of +??Adoration
@Anil replace that + with the * :)Ariannearianrhod
@RajanBalana answer provided by AminNegm-Awad solves all the cases without having to write extra code!Imprecision
@NeelamVerma then you need to go along with Amin Negm-Awad 's Answer. Cheers!Ariannearianrhod
@RajanBalana have upvoted you cheers! atleast partial output ;)Imprecision
@VinayakKini Thank you for your kindness and appreciation :)Ariannearianrhod
A
0

I think you need to subString your string, and store each number in a new NSstring(integerValue) or in Integer variable.

example:

NSString *str = @"1+2";
    int x = [[str substringToIndex:1]integerValue];
    int y = [[str substringFromIndex:1]integerValue];
    int z = x+y;
    NSLog(@"Sum === %d",z);
Aldrich answered 28/5, 2013 at 7:19 Comment(0)
K
0

Depends on complexity of your input string equations. You can use Shunting-yard algorithm for parsing mathematical equations and then calculate the equation from the Abstract Syntact Tree (AST)

But I expect you are looking for some easy, preferably already done solution. In that case you can take a try one of these (no guarantee, I haven't tried those, just googled):

Klepac answered 28/5, 2013 at 7:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.