locked
How to write a String Palindrome code RRS feed

  • Question

  • Hello,

    How can I write a String Palindrome code in VB 2008  ? I found code in java which is given below but its using reverse function to reverse the string, Do we have such function in vb 2008 ?

    http://codesgeek.com/

    Please suggest most efficient method to check String palindrome in vb 2008.




    • Edited by Anilgeek Saturday, May 3, 2014 6:44 AM edit
    Saturday, May 3, 2014 6:35 AM

Answers

  • Hello,

    How can I write a String Palindrome code in VB 2008  ? I found code in java which is given below but its using reverse function to reverse the string, Do we have such function in vb 2008 ?

    http://codesgeek.com/

    Please suggest most efficient method to check String palindrome in vb 2008.




    I think the most efficient method would be to create one string with the text you want to check as a palindrome. Then another string with that text reversed. Then test if the first string.ToUpper (to make all characters uppercase for the test as a palindrome that begins with an upper case character when reversed will end with the uppercase character and the strings will not equal each other then even though all characters are the same. For example Kayak would not equal kayaK in a string test unless all characters were converted to upper or lower case for the test.) equals the second string.ToUpper as a boolean.


    La vida loca

    Saturday, May 3, 2014 7:39 AM
  • You can go through the first half of the string comparing the characters to the ones coming from the other end:

    Module Module1
    
        Function IsPalindrome(s As String) As Boolean
            If s.Length <= 1 Then Return True
    
            For i = 0 To s.Length \ 2
                If String.Compare(s(i), s(s.Length - i - 1), StringComparison.CurrentCultureIgnoreCase) <> 0 Then
                    Return False
                End If
            Next
    
            Return True
    
        End Function
    
        Sub Main()
            Console.WriteLine(IsPalindrome("Kayak")) ' outputs "True"
            Console.ReadLine()
    
        End Sub
    
    End Module

    It is a little bit more awkward if you want to ignore punctuation: "Madam, I'm Adam" is often considered to be a palindrome.

    HTH,

    Andrew


    Saturday, May 3, 2014 2:10 PM
  • Making use of Andrew's Regex statement and the StrReverse function, here is my updated code.  It includes a separate teststring which is altered, preserving the original string.

            Dim mystring, teststring As String
            Console.Write("Enter your string:  ")
            mystring = Console.ReadLine()
            teststring = mystring           'preserve the original string
            teststring = Text.RegularExpressions.Regex.Replace(teststring, "[\W]", "")  'all punctuation & spaces removed
            teststring = teststring.ToLower()
            If mystring <> teststring Then
                Console.WriteLine("String was altered:  " & teststring)
            End If
            If teststring = StrReverse(teststring) Then
                Console.WriteLine("Your string is a palindrome.")
            Else
                Console.WriteLine("Your string is not a palindrome.")
            End If
            Console.ReadLine()


    Solitaire


    Sunday, May 4, 2014 12:25 AM

All replies

  • StrReverse()

    Dim word, rev As String word = "abcdefg" rev = StrReverse(word)

    If word = rev Then 'word is a palindrome



    Solitaire


    • Proposed as answer by Mr. Monkeyboy Saturday, May 3, 2014 7:26 AM
    • Edited by Solitaire Saturday, May 3, 2014 2:37 PM
    Saturday, May 3, 2014 6:56 AM
  • Hello,

    How can I write a String Palindrome code in VB 2008  ? I found code in java which is given below but its using reverse function to reverse the string, Do we have such function in vb 2008 ?

    http://codesgeek.com/

    Please suggest most efficient method to check String palindrome in vb 2008.




    I think the most efficient method would be to create one string with the text you want to check as a palindrome. Then another string with that text reversed. Then test if the first string.ToUpper (to make all characters uppercase for the test as a palindrome that begins with an upper case character when reversed will end with the uppercase character and the strings will not equal each other then even though all characters are the same. For example Kayak would not equal kayaK in a string test unless all characters were converted to upper or lower case for the test.) equals the second string.ToUpper as a boolean.


    La vida loca

    Saturday, May 3, 2014 7:39 AM
  • You can go through the first half of the string comparing the characters to the ones coming from the other end:

    Module Module1
    
        Function IsPalindrome(s As String) As Boolean
            If s.Length <= 1 Then Return True
    
            For i = 0 To s.Length \ 2
                If String.Compare(s(i), s(s.Length - i - 1), StringComparison.CurrentCultureIgnoreCase) <> 0 Then
                    Return False
                End If
            Next
    
            Return True
    
        End Function
    
        Sub Main()
            Console.WriteLine(IsPalindrome("Kayak")) ' outputs "True"
            Console.ReadLine()
    
        End Sub
    
    End Module

    It is a little bit more awkward if you want to ignore punctuation: "Madam, I'm Adam" is often considered to be a palindrome.

    HTH,

    Andrew


    Saturday, May 3, 2014 2:10 PM
  • Very nice Andrew.  :)

    Option Strict On
    
    Module Module1
        Sub Main()
            Do
                Console.WriteLine("Enter a line of text (""exit"" to quit)")
                Console.Write(":>")
                Dim word As String = Console.ReadLine
                If word.ToLower = "exit" Then Exit Do
                If IsPalindrome(word) Then
                    Console.WriteLine("That text is a Palindrome!")
                Else
                    Console.WriteLine("That text is not a Palindrome.")
                End If
                Console.WriteLine()
            Loop
        End Sub
    
        Public Function IsPalindrome(value As String) As Boolean
            If value.Length < 2 Then Return True
            Dim chrs = From c As Char In value Let cl = Char.ToLower(c)
                       Where Char.GetUnicodeCategory(cl) = Globalization.UnicodeCategory.LowercaseLetter
            Dim count As Integer = chrs.Count
            For i As Integer = 0 To CInt(count / 2)
                If Not chrs(i).cl = chrs(count - i - 1).cl Then Return False
            Next
            Return True
        End Function
    End Module
    


    Reed Kimble - "When you do things right, people won't be sure you've done anything at all"



    • Edited by Reed KimbleMVP Sunday, May 4, 2014 12:57 AM added error checking
    Saturday, May 3, 2014 6:07 PM
  • Very nice Andrew.  :)

    Aww, why do you have to go and say that when I'm going to point out your code doesn't compile with Option Strict On? :(

    And it throws an exception for value.Length < 2.

    So, it's your turn to find something wrong with my idea to ignore punctuation :)

    Function IsPalindrome(s As String) As Boolean
        If s.Length <= 1 Then Return True
    
        s = Text.RegularExpressions.Regex.Replace(s, "[\W]", "")
    
        If s.Length <= 1 Then Return True
    
        For i = 0 To s.Length \ 2
            If String.Compare(s(i), s(s.Length - i - 1), StringComparison.CurrentCultureIgnoreCase) <> 0 Then
                Return False
            End If
        Next
    
        Return True
    
    End Function
    

    --
    Andrew

    Saturday, May 3, 2014 9:41 PM
  • Making use of Andrew's Regex statement and the StrReverse function, here is my updated code.  It includes a separate teststring which is altered, preserving the original string.

            Dim mystring, teststring As String
            Console.Write("Enter your string:  ")
            mystring = Console.ReadLine()
            teststring = mystring           'preserve the original string
            teststring = Text.RegularExpressions.Regex.Replace(teststring, "[\W]", "")  'all punctuation & spaces removed
            teststring = teststring.ToLower()
            If mystring <> teststring Then
                Console.WriteLine("String was altered:  " & teststring)
            End If
            If teststring = StrReverse(teststring) Then
                Console.WriteLine("Your string is a palindrome.")
            Else
                Console.WriteLine("Your string is not a palindrome.")
            End If
            Console.ReadLine()


    Solitaire


    Sunday, May 4, 2014 12:25 AM
  • LOL those are easy fixes.  =P

    Reed Kimble - "When you do things right, people won't be sure you've done anything at all"

    Sunday, May 4, 2014 12:54 AM
  • ...

    So, it's your turn to find something wrong with my idea to ignore punctuation :)

    Nope, can't find any.  ;)

    Looks like Regex is faster than LINQ as well.  I wonder if manually writing the loop would beat LINQ...


    Reed Kimble - "When you do things right, people won't be sure you've done anything at all"

    Sunday, May 4, 2014 1:08 AM
  • ...

    So, it's your turn to find something wrong with my idea to ignore punctuation :)

    Nope, can't find any.  ;)

    Looks like Regex is faster than LINQ as well.  I wonder if manually writing the loop would beat LINQ...


    Reed Kimble - "When you do things right, people won't be sure you've done anything at all"

    LOL, oh yeah it does:

    Public Function IsPalindrome3(value As String) As Boolean
        If value.Length < 2 Then Return True
        Dim chrs(value.Length - 1) As Char
        Dim index As Integer
        For Each c As Char In value
            If Char.IsLetter(c) Then
                chrs(index) = Char.ToLower(c)
                index += 1
            End If
        Next
        Dim count As Integer = index
        For i As Integer = 0 To CInt(count / 2)
            If Not chrs(i) = chrs(count - i - 1) Then Return False
        Next
        Return True
    End Function
    


    Reed Kimble - "When you do things right, people won't be sure you've done anything at all"

    Sunday, May 4, 2014 1:13 AM
  • Whoops, I had the terms backward in that LINQ statement so it was evaluating too many items, that's why it was slower than regex.  The statement should have been:

    Dim chrs = From c As Char In value
               Where Char.IsLetter(c)
               Let cl = Char.ToLower(c)
    

    The LINQ solution pays a hefty price for its first execution, but all calls after that average a little faster than the Regex solution.

    However, its all really moot since the manual solution is an order of magnitude faster than any of the others. =P


    Reed Kimble - "When you do things right, people won't be sure you've done anything at all"

    Sunday, May 4, 2014 1:28 AM
  • Very nice Andrew.  :)

    Aww, why do you have to go and say that when I'm going to point out your code doesn't compile with Option Strict On? :(

    And it throws an exception for value.Length < 2.

    So, it's your turn to find something wrong with my idea to ignore punctuation :)

    Function IsPalindrome(s As String) As Boolean
        If s.Length <= 1 Then Return True
    
        s = Text.RegularExpressions.Regex.Replace(s, "[\W]", "")
    
        If s.Length <= 1 Then Return True
    
        For i = 0 To s.Length \ 2
            If String.Compare(s(i), s(s.Length - i - 1), StringComparison.CurrentCultureIgnoreCase) <> 0 Then
                Return False
            End If
        Next
    
        Return True
    
    End Function

    --
    Andrew

    That's weird. How could it not compile with Option Strict On when Option Strict On is displayed in the code?

    Obviously I'm missing something here although I've not brought the code up in VS.


    La vida loca

    Sunday, May 4, 2014 3:18 AM
  • Option Strict On
    
    Imports System.Text
    
    Public Class Form1
    
        Dim TimeIt As New Stopwatch
    
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            Me.CenterToScreen()
        End Sub
    
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            TimeIt.Restart()
            If TextBox1.Text <> "" Then
                Dim Test As Boolean = IsThisAPalindrome(TextBox1.Text)
                If Test = True Then
                    Label1.Text = "This " & ChrW(34) & TextBox1.Text & ChrW(34) & " is a palindrome."
                ElseIf Test = False Then
                    Label1.Text = "This " & ChrW(34) & TextBox1.Text & ChrW(34) & " is not a palindrome."
                End If
            End If
            Label2.Text = "Answer found in " & TimeIt.ElapsedTicks.ToString & " millionths of a second."
        End Sub
    
    
        Private Function IsThisAPalindrome(ByVal text As String) As Boolean
            Dim Result As Boolean = False
            Dim stringBuilder = New StringBuilder()
    
            For i = 0 To text.Count - 1
                If Char.IsPunctuation(text(i)) = False Then
                    stringBuilder.Append(text(i))
                End If
            Next
    
            If stringBuilder.ToString.ToUpper = StrReverse(stringBuilder.ToString.ToUpper) Then Result = True
    
            Return Result
        End Function
    
    End Class
    


    La vida loca

    Sunday, May 4, 2014 4:36 AM
  • That's weird. How could it not compile with Option Strict On when Option Strict On is displayed in the code? Obviously I'm missing something here although I've not brought the code up in VS.

    When I posted my comment aboout that, it had "For i As Integer = 0 To count / 2", where, of course, "count / 2" gives a Double. The simple correction is to use "count \ 2" or "CInt(Math.Floor(count / 2))" (Math.Floor is to avoid banker's rounding and thus checking the middle elements twice for some odd values of count).

    --
    Andrew

    Sunday, May 4, 2014 2:38 PM