当操作数包含多个字符时解析表达式?

发布于 2024-12-27 05:31:53 字数 414 浏览 2 评论 0原文

我知道有很多关于数学表达式解析的问题。我研究并学习了将中缀字符串转换为后缀的算法,并使用后缀字符串来计算表达式的值。

但我发现的所有示例都只处理表达式的操作数仅包含一个字符的情况。例如“1+2”。

如果表达式是“1 + 123”怎么办?后缀字符串会变成“1123+”,因此无法对其进行求值。

我想到的方法是从中缀字符串中读取操作数的每个字符,并将它们暂时保存在 tempStack 中。并且,当读取操作符时,将tempStack中的操作数转换为整数,然后将其推入后缀数组。

但问题随之而来,我的操作数是整数类型,但我的运算符是字符类型。所以我不能将它们放在同一个数组中。

请建议我正确的方法来做到这一点。我知道有 API 可以完成这项工作,但我想学习这个来加强我的知识。

非常感谢。

I know there are many questions about mathematics expression parsing out there. I have researched and learned the algorithm to convert an infix string to postfix, and use the postfix string to evaluate the value of the expression.

But all of examples I have found deal only with the case that operands of the expression contain only one character. For example "1+2".

How do you do if the expression is "1 + 123"? The postfix string would become "1123+", so it's unable to be evaluated.

The method I have thought is to read each character of an operand from the infix string and temporarily keep them in a tempStack. And, when an operator is read, convert the operand in the tempStack to an integer, then push it into the postfix array.

But then the problem follows, my operands would be integer type but my operators are character type. So I can't put them in the same array.

Please suggest me the right way to do this. I know that there are APIs to do this work, but I want to learn this to strengthen my knowledge.

Thank you very much.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

笔落惊风雨 2025-01-03 05:31:53

除非您用空格分隔标记,否则您不会将输入转换为“后缀字符串”。输入“1 + 123”将变成例如“1 123 +”。但最好将令牌压入堆栈,例如字符串数组。如果您使用的语言支持代数数据类型,您将创建一个 Token 类型并压入一个 Token 堆栈。

You don't transform the input into a 'postfix string' unless you separate the tokens by whitespace. The input "1 + 123" would then become e.g. "1 123 +". But it's better to push the tokens on a stack, for example an array of strings. If the language you use supports algebraic data types, you would create a Token type and push onto a stack of Tokens.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文