1

Is there a way to parse operators in String to use in an equation?

Example: "5 + 4"

In this case, the 5 and 4 are strings, but I can parse them to integer by using a for loop, right? But what about the + operator?

Okay I used ChrisF's solution

toilabav90
  • 15
  • 6
  • 1
    You have to tokenise the string and then do explicit checks for operators: `if (token == "+")` etc. – ChrisF Feb 16 '13 at 22:59
  • That's basically it, yes. – ChrisF Feb 16 '13 at 23:06
  • how would I use the token part if there are click button events for each operator? – toilabav90 Feb 16 '13 at 23:06
  • You'd have to update your question and post more code to show what you're actually trying to achieve. – ChrisF Feb 16 '13 at 23:07
  • 1
    http://stackoverflow.com/questions/6604840/vb-net-evaluating-mathematical-expression-in-a-string – Andrew Morton Feb 16 '13 at 23:09
  • You're likely to get some answers here that recommend something like CodeDOM, Roselyn, System.Reflection.Emit, or some way of getting javascript eval()-like functionality in C#. Don't use those answers. That opens up security issues where when you expect a simple mathematical expression, you're really allowing something more like a full PowerShell instead. – Joel Coehoorn Feb 17 '13 at 02:10

1 Answers1

1

The poster seems to have solved his problem, but just in case someone finds this post looking for an answer I have made a very simple solution.

        Dim s As String = "5 * 4" 'our equation
        s = s.Replace(" ", "") 'remove spaces
        Dim iTemp As Double = 0 'double (in case decimal) for our calculations
        For i As Integer = 0 To s.Length - 1 'standard loop
            If IsNumeric(s(i)) Then
                iTemp = Convert.ToInt32(s(i)) - 48 'offset by 48 since it gets ascii value when converted
            Else
                Select Case s(i)
                    Case "+"
                        'note s(i+1) looks 1 index ahead
                        iTemp = iTemp + (Convert.ToInt32(s(i + 1)) - 48)'solution
                    Case "-"
                        iTemp = iTemp - (Convert.ToInt32(s(i + 1)) - 48)'solution
                    Case "*"
                        iTemp = iTemp * (Convert.ToInt32(s(i + 1)) - 48)'solution
                    Case "/"
                        'you should check for zero since x/0 = undefined
                        iTemp = iTemp / (Convert.ToInt32(s(i + 1)) - 48)'solution
                End Select
                Exit For 'exit since we are done
            End If
        Next
        MsgBox(iTemp.ToString)

This is just a simple quick and dirty solution. The way I learned in school (many many moons ago) was to do these types of problems with stacks. Complex mathematical strings can be parsed using stacks.

MonkeyDoug
  • 453
  • 3
  • 17