Adam Fraser Adam Fraser - 1 year ago 159 Question

Visual basic palindrome code

I am trying to create an application which will determine whether a string entered by user is a palindrome or not.

Is it possible to do without StrReverse, possibly with for next loop. That's what i have done so far.

Working one, with StrReverse:

Dim userInput As String = Me.txtbx1.Text.Trim.Replace(" ", "")
Dim toBeComparedWith As String = StrReverse(userInput)

Select Case String.Compare(userInput, toBeComparedWith, True)

Case 0
Me.lbl2.Text = "The following string is a palindrom"
Case Else
Me.lbl2.Text = "The following string is not a palindrom"

End Select

Not working one:

Dim input As String = TextBox1.Text.Trim.Replace(" ", "")
Dim pallindromeChecker As String = input
Dim output As String

For counter As Integer = input To pallindromeChecker Step -1

output = pallindromeChecker

Next counter

output = pallindromeChecker

If output = input Then
Me.Label1.Text = "output"
Me.Label1.Text = "hi"
End If

Dai Dai
Answer Source

While using string reversal works, it is suboptimal because you're iterating over the string at least 2 full times (as string reversal creates a copy of a string because strings are immutable in .NET) (plus extra iterations for your Trim and Replace calls).

However consider the essential properties of a palindrome: the first half of a string is equal to the second half of the string in reverse.

The optimal algorithm for checking a palindrome needs only iterate through half of the input string - by comparing value[n] with value[length-n] for n = 0 to length/2.


Public Shared Function IsPalindrome(String value) As Boolean

    ' Input validation.
    If value Is Nothing Then Throw New ArgumentNullException("value")
    value = value.Replace(" ", "")

    Dim length As Integer = value.Length
    ' Shortcut case if the input string is empty.
    If length = 0 Then Return False ' or True, depends on your preference

    ' Only need to iterate until half of the string length.
    ' Note that integer division results in a truncated value, e.g. (5 / 2 = 2)...
    '... so this ignores the middle character if the string is an odd-number of characters long.
    For i As Integer = 0 To length  / 2

        If value(i) <> value(length-i) Then
            ' Shortcut: we can abort on the first mismatched character we encounter, no need to check further.
            Return False
        End If

    Next i

    ' All "opposite" characters are equal, so return True.
    Return True

End Function
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download