Is there way to solve the string equations in ios
?
For example
Input:
NSString * str =@\"1+2\";
Output:
<
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.