Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace TEST_ExpressionParser
- {
- static class ExpressionEvaluator
- {
- private static int Priority(char op)
- {
- if (op == '+' || op == '-') return 1;
- if (op == '*' || op == '/' || op == '%') return 2;
- if (op == '^') return 3;
- return 0;
- }
- private static bool IsOperand(char c)
- {
- if (!char.IsLetterOrDigit(c)) return false;
- return true;
- }
- private static bool IsOperator(char c)
- {
- return (c == '+' || c == '-' || c == '*' || c == '/' || c == '%' || c == '^');
- }
- private static string GetOperand(string text, ref int start)
- {
- StringBuilder str = new StringBuilder();
- while (start < text.Length && (char.IsLetterOrDigit(text[start]) || text[start] == '.'))
- {
- str.Append(text[start]);
- start++;
- }
- start--;
- return str.ToString();
- }
- public static string ConvertToPostfix(string input)
- {
- Stack<char> stack = new Stack<char>();
- StringBuilder str = new StringBuilder();
- // To avoid confusion, replace negative numbers with 0 - number
- if (input[0] == '-') input = input.Insert(0, "0");
- while (input.Contains("( ")) input = input.Replace("( ", "(");
- input = input.Replace("(-", "(0-");
- for (int i = 0; i < input.Length; i++)
- {
- if (char.IsWhiteSpace(input[i])) continue;
- if (IsOperand(input[i]))
- {
- str.Append(GetOperand(input, ref i));
- str.Append(' ');
- }
- else if (input[i] == '(') stack.Push('(');
- else if (input[i] == ')')
- {
- while (stack.Peek() != '(')
- {
- str.Append(stack.Pop());
- str.Append(' ');
- }
- stack.Pop();
- }
- else if (IsOperator(input[i]))
- {
- if (stack.Count == 0) stack.Push(input[i]);
- else
- {
- while (stack.Count != 0 && Priority(input[i]) <= Priority(stack.Peek()))
- {
- str.Append(stack.Pop());
- str.Append(' ');
- }
- stack.Push(input[i]);
- }
- }
- }
- while (stack.Count > 0)
- {
- str.Append(stack.Pop());
- str.Append(' ');
- }
- return str.ToString();
- }
- private static double EvalSmall (double a, double b, char op)
- {
- switch (op)
- {
- case '+': return a + b;
- case '-': return a - b;
- case '*': return a * b;
- case '/': return a / b;
- case '%': return a % b;
- case '^': return Math.Pow(a, b);
- }
- return 0;
- }
- public static double ParsePostfix(string text)
- {
- Stack<double> stack = new Stack<double>();
- for (int i = 0; i < text.Length; i++)
- {
- if (char.IsWhiteSpace(text[i])) continue;
- if (IsOperand(text[i])) stack.Push(double.Parse(GetOperand(text, ref i)));
- else if (IsOperator(text[i])) {
- double a = stack.Pop();
- double b = stack.Pop();
- stack.Push(EvalSmall(b, a, text[i]));
- }
- }
- return stack.Peek();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement