I'm writing a simple calculator app, before evaluating a statement, it checks to make sure that any parentheses are formatted correctly. It initially checks that there is the same amount of opening (
and closing )
parentheses. And if there are, then it will check that they are in the correct order.
unlike this: 6) / (1 + 4)8 + (5
.
In order to that I used this code:
Chkp("(1+1/2)+(2+3)")
which would call:
Function ChkP(text As String)
For i As Integer = 0 To CountOf(text, "(") - 1
If CharIndex(text, "(", i) > CharIndex(text, ")", i) Then Return False
Next
Return True
End Function
which would then call:
Function CharIndex(text As String, character As String, ByRef index As Integer)
For x As Integer = 0 To text.Length - 1
If text(x) = character Then
index -= 1
If index = -1 Then
Return x
End If
End If
Next
Return -1
End Function
If Chkp
should return False
the parentheses are wrong otherwise they are correct, however, the output is always that the parentheses are invalid, even if the are correct.
Is there a way to fix this? Or is there just a better way of checking parentheses altogether?
Any help is greatly appreciated.