Convert NSString of a math equation to a value

前端 未结 3 549
温柔的废话
温柔的废话 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: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.

提交回复
热议问题