[Solved] Parse string with arithmetic operation [duplicate]


Maybe using regular expressions you can do something like…

String sExpression = "23 + 323 =";
int nResult = 0;
Match oMatch = Regex.Match(@"(\d+)\s*([+-*/])\s*(\d+)(\s*=)?")
if(oMatch.Success)
{
    int a = Convert.ToInt32(oMatch.Groups[1].Value);
    int b = Convert.ToInt32(oMatch.Groups[3].Value);
    switch(oMatch.Groups[2].Value)
    {
        case '+';
            nResult = a + b;
            break;
        case '-';
            nResult = a - b;
            break;
        case '*';
            nResult = a * b;
            break;
        case "https://stackoverflow.com/";
            nResult = a / b;
            break;
    }
}

and extend to your need.. (floats, other operators, validations, etc)

4

solved Parse string with arithmetic operation [duplicate]