Convert NSString of a math equation to a value

前端 未结 3 543
温柔的废话
温柔的废话 2020-12-11 04:37

I would like to know how to evaluate a string representation of an equation as if it were a real equation:

if(@\"15+14==23\")
{
    //True statement...
}
els         


        
相关标签:
3条回答
  • 2020-12-11 05:25

    Here is an example how to do it with NSPredicate:

    NSPredicate *p = [NSPredicate predicateWithFormat:@"1+2==3"];
    NSLog(@"%d", [p evaluateWithObject:nil]);
    p = [NSPredicate predicateWithFormat:@"1+2==4"];
    NSLog(@"%d", [p evaluateWithObject:nil]);
    

    The first NSLog produces 1 because 1+2==3 is true; the second produces 0.

    0 讨论(0)
  • 2020-12-11 05:29
    NSString *equation = @"15+14==29";
    
    
    NSPredicate *pred = [NSPredicate predicateWithFormat:equation];
    
    NSExpression *LeftExp = [pred leftExpression];
    
    NSExpression *RightExp = [pred rightExpression];    
    
    
    NSNumber *left = [LeftExp expressionValueWithObject:nil context:nil];
    
    NSNumber *right = [RightExp expressionValueWithObject:nil context:nil];
    
    
    if ([left isEqualToNumber:right]) {
        NSLog(@"yes left is equal to right");
    }
    else{
        NSLog(@"yes left is NOT equal to right");
    
    }
    
    NSLog(@"left %@", left); 
    
    NSLog(@"right %@", right); 
    
    0 讨论(0)
  • 2020-12-11 05:36

    So, this is a problem that I believe is a lot more complicated than the linked question lets on (although the question is asking for a "simple" equation parser).

    Fortunately for you, I think this is a really interesting problem and have already written one for you: DDMathParser.

    It has a good amount of documentation, including things like how to add it to your project and a high overview of its capabilities. It supports all of the standard mathematical operators, including logical and comparison operators (||, &&, ==, !=, <=, etc).

    In your case, you'd do something like this:

    NSNumber *result = [@"15+14 == 23" numberByEvaluatingString];
    if ([result boolValue] == YES) {
      ....True statement....
    } else {
      .....False statement.....
    }
    

    As a heads up, DDMathParser is made available under the MIT license, which requires you to include the copyright information and the full text of the license in anything that uses it.

    0 讨论(0)
提交回复
热议问题