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
}
CodePudding user response:
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.