public List<string> StringInterpreter(string equation) { int x = 1; List<string> list = new List<string>() { }; Regex regex = new Regex(@"(\d*\.?\d*)"); Regex regex1 = new Regex(@"[*+/-]"); MatchCollection matches = regex.Matches(equation); MatchCollection matches1 = regex1.Matches(equation); foreach (Match match in matches) { list.Add(Convert.ToString(match)); } foreach (Match match in matches1) { list.Insert(x, Convert.ToString(match)); x += 3; } return list; }
/// <summary> /// Finds the first instance of currentOperator (i.e. '+'), takes the operands on the left and right /// to the operator and builds an Expression instance (i.e. AddExpression in case of '+'). /// </summary> /// <param name="expression">A list containing numbers, operators and expressions.</param> /// <param name="currentOperator">The symbol of the current operator to be processed.</param> private static void CreateExpression(List<dynamic> expression, char currentOperator) { int operatorIndex = expression.IndexOf(currentOperator); Expression operation; dynamic leftOperand, rightOperand; try { if (expression.ElementAt(operatorIndex - 1) is double) { leftOperand = new NumberExpression(expression.ElementAt(operatorIndex - 1)); } else if (expression.ElementAt(operatorIndex - 1) is Expression) { leftOperand = expression.ElementAt(operatorIndex - 1); } else { throw new ArgumentException("Invalid expression string."); } if (expression.ElementAt(operatorIndex + 1) is double) { rightOperand = new NumberExpression(expression.ElementAt(operatorIndex + 1)); } else if (expression.ElementAt(operatorIndex + 1) is Expression) { rightOperand = expression.ElementAt(operatorIndex + 1); } else { throw new ArgumentException("Invalid expression string."); } } catch (Exception ex) { throw new ArgumentException("Invalid expression string."); } switch (currentOperator) { case '+': operation = new AddExpression(leftOperand, rightOperand); break; case '-': operation = new SubtractExpression(leftOperand, rightOperand); break; case '*': operation = new MultiplyExpression(leftOperand, rightOperand); break; case '/': operation = new DivideExpression(leftOperand, rightOperand); break; default: operation = new NumberExpression(0); break; } expression.RemoveAt(operatorIndex + 1); expression.RemoveAt(operatorIndex); expression.RemoveAt(operatorIndex - 1); expression.Insert(operatorIndex - 1, operation); }