简体   繁体   中英

java: Splitting arithmetic expresssion into tokens

您如何用空格分隔算术表达式,例如我有22+(33 * 1)这个表达式,我想用相同的字符串(返回字符串)中的运算符之间的空格来分隔它们,例如22 +(33 * 1),我使用StringTokenizer的方式

Your rule is simpler then you think. Probably correct java:

expr = expr.replaceAll('+', ' + ')
           .replaceAll('-', ' - ')
           .replaceAll(')', ' ) ')
           //etc
           .replaceAll(' ', '  '); //remove any double spaces added.

That is Not Easy. You have to parse the Expression and Build up a tree of tokens. You Finally behave like A parser. Then you recreate the Expression and insert a Space between Each element.
try to search for parsing arithmetic expressions

您可以使用多个String.replaceAll语句将运算符替换为带空格的运算符。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM