سؤال

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.

هل كانت مفيدة؟

المحلول

The easiest approach to check that parentheses are balanced and a close parenthesis always comes after a corresponding open parenthesis is:

  1. Initialize a nesting level variable to 0.
  2. For each character of the text: if the character is '(', add 1 to the nesting level; if the character is ')', then subtract 1 from the nesting level and if the nesting level is then negative, immediately report failure.
  3. At the end, report success if and only if the nesting level is 0.
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top