Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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, e.g. 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 e.g. string.split("") but missing something in the logic.

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading