简体   繁体   中英

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 . 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" . I have explored delimiting by every character eg string.split("") but missing something in the logic.

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:

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

Above expression would produce [11, +, 1, +, 1] as its result so you can iterate through the result as is.

Likewise, "11+1+1".split("\\b") would produce [-, 11, +, 1, +, 1] as a result. This should not make it any harder to interpret the operation itself.

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