-2

I have a string which consists of numbers separated by either addition, subtraction, multiplication, division signs etc, eg:

"1+2*3"="7".

The maximum number of signs can be two. I want to compute this string as an arithmetic operation. How can I do this? My current thinking is to split this string into a list then calculate the result using the normal order of arithmetic operation.

Ajit Goel
  • 4,180
  • 7
  • 59
  • 107
  • 1
    Will you please post what you have tried till now... – Manish Apr 23 '16 at 04:06
  • You really don't want that in a list. A simple and effective way to do what you're asking is with the Shunting Yard algorithm. See http://stackoverflow.com/questions/29634992/shunting-yard-validate-expression – Jim Mischel Apr 23 '16 at 04:14
  • you can use regular expression to catch numbers for example `(\d)` is proper for you please check below link https://regex101.com/r/kP9iX9/1 – Hadi Apr 23 '16 at 04:15
  • You say "Once I have this string into a list I can then calculate the result using the normal order of arithmetic", but no, you can't. You need to do the multiplication before the addition in your example. You need a tree structure to evaluate mathematical expressions. – Enigmativity Apr 23 '16 at 07:21
  • So whoever downvoted for the answer can you please explain why? – Ajit Goel Apr 23 '16 at 14:29

3 Answers3

1

You can use the the built in DataTable.Compute method instead of coding it yourself :

var result = new DataTable().Compute("1+2*3", null); // Will result in 7

Edit :

DataTable do not implement Dispose method so it is safe to use them that way. However it does not get uglier if you wrap them in a using statement. See a related SO post.

Community
  • 1
  • 1
Fabien ESCOFFIER
  • 4,751
  • 1
  • 20
  • 32
0

I was able to take care of this issue without splitting the string into separate elements(and then applying the rules of arithmetic operations).

using System;
using System.Data;
 public int Maths(string operation)
        {
            object result=new DataTable().Compute(operation, null);
            return Int32.Parse(result.ToString());
        }
Ajit Goel
  • 4,180
  • 7
  • 59
  • 107
0

You can use any of the numerous parser generators. Most popular in .NET platfrom, I think, is Antlr. Or, even, you can write parser from scratch using Pratt algorytm, it's pretty easy. Clear guide - http://journal.stuffwithstuff.com/2011/03/19/pratt-parsers-expression-parsing-made-easy/

reptile
  • 175
  • 1
  • 9