简体   繁体   English

将字符串输入拆分为离散数字和运算符

[英]Splitting string input into discrete numbers and operators

I am trying to split a string like "-10 5 + 3 *" into component parts to use in basic arithmetic, while maintaining the integrity of operators, eg not confusing -10 for the - operator and a 10 .我正在尝试将像"-10 5 + 3 *"这样的字符串拆分成组成部分以用于基本算术,同时保持运算符的完整性,例如不要将-10-运算符和10混淆。 How should I approach this?我应该如何处理这个问题?

Currently I am doing a simple split based on a space delimiter, and intend to write individual methods to deal with each operation.目前我正在做一个基于空格分隔符的简单拆分,并打算编写单独的方法来处理每个操作。 However this does not account for inputs with no spaces: example "11+1+1" .但是,这不考虑没有空格的输入:例如"11+1+1" I have explored delimiting by every character eg string.split("") but missing something in the logic.我已经探索了每个字符的定界,例如string.split("")但在逻辑上遗漏了一些东西。

String[] simplifyCommand(String s) {
    return s.split(" ");
    //or s.split(""); for individual characters
  }

You can use the \b word boundary regex anchor to split your input string into digits and operators:您可以使用\b字边界正则表达式锚将输入字符串拆分为数字和运算符:

"11+1+1".split("\\b");

Above expression would produce [11, +, 1, +, 1] as its result so you can iterate through the result as is.上面的表达式会产生[11, +, 1, +, 1]作为结果,因此您可以按原样遍历结果。

Likewise, "11+1+1".split("\\b") would produce [-, 11, +, 1, +, 1] as a result.同样, "11+1+1".split("\\b")会产生[-, 11, +, 1, +, 1]作为结果。 This should not make it any harder to interpret the operation itself.这不应该使解释操作本身变得更加困难。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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