Equation (expression) parser with precedence?

前端 未结 23 1937
遇见更好的自我
遇见更好的自我 2020-11-22 11:44

I\'ve developed an equation parser using a simple stack algorithm that will handle binary (+, -, |, &, *, /, etc) operators, unary (!) operators, and parenthesis.

<
23条回答
  •  甜味超标
    2020-11-22 12:16

    It depends on how "general" you want it to be.

    If you want it to be really really general such as be able to parse mathematical functions as well like sin(4+5)*cos(7^3) you will probably need a parse tree.

    In which, I do not think that a complete implementation is proper to be pasted here. I'd suggest that you check out one of the infamous "Dragon book".

    But if you just want precedence support, then you could do that by first converting the expression to postfix form in which an algorithm that you can copy-and-paste should be available from google or I think you can code it up yourself with a binary tree.

    When you have it in postfix form, then it's piece of cake from then on since you already understand how the stack helps.

提交回复
热议问题