Hi all

I am trying to write a program to recognizing word or phrase is a palindrome or not.
Please help me

Regards
Aura

Recommended Answers

All 7 Replies

Use StrReverse() function to reserve the word/phrase. Compare the real words/phrase with reserved words/phrase.
Check out the result if it same or not.

Private Sub Command1_Click()
    Dim Palindrome As String

    Palindrome = StrReverse(Text1.Text)

    If StrComp(Text1.Text, Palindrome, vbTextCompare) = 0 Then
        MsgBox "Palindrome!"
    Else
        MsgBox "Not a Palindrome!"
    End If
End Sub

But before you reverse the string you should normalize it.

  1. convert everything to upper or lower case
  2. remove all non-letters

If you were to check the phrase "Able was I ere I saw Elba" without normalizing it would not be flagged as a palindrome. After normalizing it would be "ablewasiereisawelba" which would be flagged as a palindrome.

If you were to check the phrase "Able was I ere I saw Elba" without normalizing it would not be flagged as a palindrome. After normalizing it would be "ablewasiereisawelba" which would be flagged as a palindrome.

Nope. It also recognized as palindrome. StrReverse will completed reverse the words included the space.

Sir Jim's example would be flagged as palindrome because the spaces are symmetrical.

How about this one? "A nut for a jar of tuna". Without normalizing, it will not be flagged as one.

A nut for a jar of tuna

That makes sense.
@reverend jim and scidzilla : Thanks for correcting
@Aura : this following codes is modified with other members suggestion :

Function RemoveNonLetterChar(theString)
    strAlphaNumeric = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
    For i = 1 To Len(theString)
        strChar = Mid(theString, i, 1)
        If InStr(strAlphaNumeric, strChar) Then
            CleanedString = CleanedString & strChar
        End If
    Next
    RemoveNonLetterChar = CleanedString
End Function

Private Sub Command1_Click()
    Dim Temp, Palindrome As String

    Temp = LCase(RemoveNonLetterChar(Text1.Text)) 'lower case and remove non letters char
    Palindrome = StrReverse(Temp)

    If StrComp(Temp, Palindrome, vbTextCompare) = 0 Then
        MsgBox "Palindrome!"
    Else
        MsgBox "Not a Palindrome!"
    End If
End Sub

This is perfect.
Thank you all.

Sir Jim's example would be flagged as palindrome because the spaces are symmetrical.

Only if you did the compare case-insensitive. But I suppose I could have picked a better example. Madam, I'm Adam would have been better. Or A man, a plan, a canal. Panama.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.