1

有没有办法解析字符串中的运算符以在方程式中使用?

示例:“5 + 4”

在这种情况下,5 和 4 是字符串,但我可以使用 for 循环将它们解析为整数,对吧?但是 + 运算符呢?

好的,我使用了 ChrisF 的解决方案

4

1 回答 1

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.

于 2013-02-17T01:15:10.203 回答