Quantcast
Channel: VBForums - Code It Better
Viewing all articles
Browse latest Browse all 16

Format Expression

$
0
0
I wrote this function to format expressions to where there is a space after each character with the exception of unary operators and the last character:

Code:

Private Function FormatExpression(ByVal expression As String) As String
    'Add a space after any '(' and a space before any ')'
    expression = expression.Replace("(", "( ").Replace(")", " )")

    For index As Integer = expression.Length - 1 To 1 Step -1
        Dim currentChar As String = expression(index)

        'Check if the current character is a possible unary operator
        If {"+", "-", "*", "/", "^"}.Contains(currentChar) Then
            'If it is an operator check if the prior character that's not a whitespace is NOT an operator
            Dim tempSource As String = expression.Substring(0, index).Replace(" ", String.Empty)

            'If the character before the current one is an operator too, then we have a unary operator
            If Not {"+", "-"}.Contains(tempSource(index - (expression.Substring(0, index).Length - tempSource.Length)
                'So if the prior character is not a unary operator, add a space after it
                expression = expression.Insert(index + 1, " ")
            End If

            'Regardless of if the operator is a unary operator or not add a space before it
            expression = expression.Insert(index, " ")
        End If
    Next

    'Return the string with no excess whitespace
    Return String.Join(" ", expression.Split(New Char() {}, StringSplitOptions.RemoveEmptyEntries))
End Function

It works great, but can I improve it?

Viewing all articles
Browse latest Browse all 16

Trending Articles