okay, so let me just get this right: you have a text box that contains the text "2 + 4" or "3 * 6", and the code that you use to get the answer to pop up in a text box? I really hope I have misunderstood something powerful, for it must be the worst, slow thing, hopeless solution to such a problem can be found at.
It is so easy that you only have "a + b", "ab", "a * b" or "a/b", I would perhaps done something like:
Code:
class Program
{
public delegate double MyDelegate(double a, double b);
static void Main (string[] args)
{
string math = "2 - 3";
Console.WriteLine (Parse(math));
math = "12432 * 234234";
Console.WriteLine (Parse(math));
math = "1345 / 123542";
Console.WriteLine (Parse(math));
Console.Read ();
}
static double Parse (string math)
{
string pattern = @"^\s*(?<a>\d+)\s*(?<operator>(\+|\-|\*|\/))\s*(?<b>\d+)\s*$";
if (Regex.IsMatch(math, pattern, RegexOptions.IgnorePatternWhitespace))
{
Match match = Regex.Match (math, pattern, RegexOptions.IgnorePatternWhitespace);
MyDelegate del = GetDelegate(match.Groups["operator"].Value);
return del(double.Parse(match.Groups["a"].Value), double.Parse(match.Groups["b"].Value));
}
else
throw new Exception ("parameter does not seem valid");
}
static MyDelegate GetDelegate (string op)
{
switch (op)
{
case "+":
return new MyDelegate (Add);
case "-":
return new MyDelegate (Subtract);
case "*":
return new MyDelegate (Multiply);
case "/":
return new MyDelegate (Divide);
default:
throw new Exception ("Invalid operator");
}
}
static double Add (double a, double b)
{
return a + b;
}
static double Subtract (double a, double b)
{
return a - b;
}
static double Multiply (double a, double b)
{
return a * b;
}
static double Divide (double a, double b)
{
if (b! = 0)
return (a/b);
throw new DivideByZeroException ();
}
}
However, there is no good solution if the problem is not always as static.
Bookmarks