I'm implementing the Shunting Yard Algorithm in Java, as a side project to my AP Computer Science class. I've implemented a simple one in Javascript, with only basic arithmetic expressions (addition, subtraction, multiplication, division, exponentiation). To split that into an array, what I did was find each of the operators (+-*/^
), as well as numbers and parentheses, and I put a space around them, and then I split it into an array. For example, the infix string 4+(3+2)
would be made into 4 + ( 3 + 2 )
, and then split on whitespace.
However, I feel that this method is very slow, and it gets increasingly harder and inefficient to implement as you start to add mathematical functions, such as sine, cosine, tangent, absolute value, and others.
What would be the best way to split a string like sin(4+3)-8
into an array ["sin","(" 4,"+",3,")","-",8]
?
I could use regex for this, but I don't really understand them well, and I'm trying to learn them, so if that would be the best solution to them, could the answerer please explain what it does?