How to evaluate the string equation in ios

后端 未结 6 1256
一向
一向 2020-12-15 19:48

Is there way to solve the string equations in ios ?

For example

Input:

NSString * str =@\"1+2\";

Output:

<

6条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-15 20:14

    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.

提交回复
热议问题