Balanced expression

The code demonstrates how to find balanced expression. Each opening bracket is checked against the closing bracket. The expression is balanced if it finds the corresponding closing bracket else it is unbalanced.


Private Sub BalancedExpression()
Dim strExpr(200) As String
Dim intI, intTop As Integer
Dim strExpression As String

strExpression = "(A+{B/(C*D)}/(E-[F/G]))" 'Balances equation
'strExpression = "(A+{B/C)*(D-E)/(F*(G/H)/I)))" 'Unbalanced equation
intTop = -1
For intI = 1 To strExpression.Length
'Consider every character from the expression
If Mid$(strExpression, intI, 1) = "(" Or Mid$(strExpression, intI, 1) = "{" Or Mid$(strExpression, intI, 1) = "[" Then
'Insert the opening bracket in the array.
intTop = intTop + 1
strExpr(intTop) = Mid$(strExpression, intI, 1)
ElseIf Mid$(strExpression, intI, 1) = ")" Then
'Check the corresponding bracket
If strExpr(intTop) = "(" Then
intTop = intTop - 1
Else
MessageBox.Show("Unbalances expression")
Exit Sub
End If
ElseIf Mid$(strExpression, intI, 1) = "}" Then
If strExpr(intTop) = "{" Then
intTop = intTop - 1
Else
MessageBox.Show("Unbalanced expression")
Exit Sub
End If
ElseIf Mid$(strExpression, intI, 1) = "]" Then
If strExpr(intTop) = "[" Then
intTop = intTop - 1
Else
MessageBox.Show("Unbalanced expression")
Exit Sub
End If
End If
Next
If intTop = -1 Then
MessageBox.Show("Balanced equation")
Else
MessageBox.Show("Unbalanced equation")
End If
End Sub


Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: