0

I've been stuck trying different methods of doing this for a while, usually not getting anywhere productive. I've tried going down each operator and splitting the string and evaluating there, I've tried looping through each character and then checking the next character but nothing seems to work very well and efficiently.

Is there a way to do this easily? I'd want to input a string, for example, "4*4+1/1" and receive an output of 17. Or, "4^2*2" = 14

ryan
  • 23
  • 4
  • Do you trust the input? Then, you could just evaluate the string. Otherwise, you need to parse the string character by character and build a reasonable data structure which can then be evaluated. This is much more complex. – ssc-hrep3 Dec 22 '19 at 00:48
  • The inputs will always be valid, so how do I evaluate the string then? – ryan Dec 22 '19 at 01:35
  • Start from splitting the string by an array of all known signs. – preciousbetine Dec 22 '19 at 05:16
  • Regex it with something like `[(\*)(\+)(\-)(\/)(\^)]`. For example, if you regex this: `"(4+2)*((4+8)/2)-5^2"` you'll see from the matches that the first `+` has `(` on the left (the match before) and `)` on the right (the match after). So this `+` has priority over the next `*`, while it doesn't when there are no `()` symbols. On `((4+8)/2)`, you see that the `+` match has two matches on the left and one on the right, then another symbol with *higher priority*, then another matched `)`. Go with the flow. Btw, `4^2*2` `<> 14`. – Jimi Dec 22 '19 at 05:42
  • Note that each `Match` object not only references the matched symbol, but also its position inside the string. – Jimi Dec 22 '19 at 05:49
  • Does this answer your question? [Simplifying and evaluating mathematical strings](https://stackoverflow.com/questions/59444338/simplifying-and-evaluating-mathematical-strings) – Blackwood Dec 22 '19 at 13:57

1 Answers1

0

The following will compute a string.

Private Sub CompteString()
    Dim equation As String = "2+3"
    Dim result = New DataTable().Compute(equation, Nothing)
    Debug.Print(result.ToString)
End Sub
Mary
  • 14,926
  • 3
  • 18
  • 27
  • @Antony Exponentiation is not a supported operator: see [DataColumn.Expression - Operators](https://learn.microsoft.com/en-us/dotnet/api/system.data.datacolumn.expression?view=netframework-4.8#operators). For something which will evaluate ^, please see my answer to [Simplifying and evaluating mathematical strings](https://stackoverflow.com/a/59444666/1115360). – Andrew Morton Dec 22 '19 at 13:46
  • I notice in another question, someone mentioned an open source Math.Net library that may work for parsing expressions. – Robert Richter Dec 22 '19 at 19:33