How can the format string: "-99/9" split into an array of substrings {"-","99","/","9"} ?
3 answers
Why complicate things? There are numbers and something in between. Select the numbers from both sides with spaces, normalize the string so that after splitting no empty elements appear and it’s ready.
import java.util.Arrays; public class Main { public static void main(String[] args) { String str = "2+2*24-78"; str = str.replaceAll("(\\d+)"," $1 "); str = str.trim(); String[] stack = str.split(" "); System.out.println(Arrays.toString(stack)); } } The question did not say anything about the decimal separator, functions and parentheses.
The correct approach to solving the problem is not to immediately break the string into separate lexemes, but read it sequentially by the state machine. As a basis, you can take the algorithm from the article on reverse Polish notation .
- Mitrofano What does "$ 1" mean in the replaceAll () parameter? - Vladislav Solopov
- oneThis is an alternative group access. The set of spells bounded by the brackets in a regular expression is called a group. Take an example
(reg1)(reg2). If you work through Matcher, then m.group (1) -> reg1, m.group (2) -> reg2. When working with strings, you can use an alternative entry for the found groups $ 1, $ 2, if you need to use the found value as a replacement. See an example from this article vogella.com/tutorials/JavaRegularExpressions/article.html - Sergey Mitrofanov
If the format of the string is not known in advance or it can be changed, then I would suggest the following algorithm.
- Take the length of the line
- Create an empty fill list
- Cycle through the characters. Choose a character and see whether it is numeric or not (Reduce the character to a number, then to the string and check for a match). If numeric then we look at the last element of the list and if there is also a number, then we modify by appending the last list to the end of the line.
- Are you talking about the reverse Polish entry? Do you have lists in Java? Or are you talking about arelists? - Vladislav Solopov
- @VladislavSolopov, so it is abstract. Though HashMap take, though ArrayList. Much more comfortable there and fold. In HashMap you can add flag / value. - dlarchikov
To vskidku - regular. Or something missing? It will turn out something like this:
(regex) /^(-|+)?(\d+)(\/)(\d+)$/
"--9//9-/9/-9-/-/9 9,9.9;9_9"how should it be broken? - Nick Volynkin ♦1++2,3--4,5*-6? - Nick Volynkin ♦