Hi I am trying to make some code to collect tokens of a string. but I keep getting an out of range error, tho it works with some expressions
here my code.
If you run the code with this expression eveything is fine "8 * 2 + (10+5)"Code:Public Class Form1 Private Enum Tokypes None = 0 Digit = 1 Sysmbol = 2 End Enum 'Private Expression As String = "8 * 2 + (10+5)" 'Works fine on this expression. Private Expression As String = "8 * 2 + 1" ' VB Crys on this one why Private Pos As Integer = 0 Dim sToken As String = vbNullString Dim sTokType As Tokypes Private Function isDelim(ByVal c As Char) As Boolean If (("+-/*%^=()".IndexOf(c) <> -1)) Then Return True End If Return False End Function Private Sub GetTokens() sToken = vbNullString sTokType = Tokypes.None If (Pos = Expression.Length) Then sToken = vbNullString sTokType = Tokypes.None Return End If 'Skip white While (Pos < Expression.Length) And Char.IsWhiteSpace(Expression(Pos)) Pos += 1 End While ' If isDelim(Expression(Pos)) Then sToken = sToken & Expression(Pos) Pos += 1 'Token Type. sTokType = Tokypes.Sysmbol ElseIf Char.IsDigit(Expression(Pos)) Then 'Thowing error here - Index was outside the bounds of the array. While Char.IsDigit((Expression(Pos))) sToken = sToken & Expression(Pos) Pos += 1 End While If Pos = Expression.Length Then Return 'Token Type. sTokType = Tokypes.Digit End If End Sub Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click GetTokens() While sTokType <> Tokypes.None MsgBox(sToken) GetTokens() End While End Sub End Class
But if you run it with this you get an out of range error. 8 * 2 + 1
I don't see why cos the first expression has more length than the second.




Reply With Quote