Test if a string is a palindrome

This is the first in a short series in which I’ll look at some string handling techniques.  PowerShell is all about objects but sometimes you just have to work with the basics. In this post I’ll show how to test in a string is a palindrome.

A palindrome is a list of characters that read the same backwards as well as forwards. Radar is a word that is the same when reversed for example – its a simple palindrome. You can have phrases that are palindromes as well.

function test-palindrome {
   [CmdletBinding()]
   param (
     [string]$teststring
   )

  Write-Verbose -Message “Input string: $teststring”
   $cr = $teststring.ToCharArray()
  
   $ca = $cr | where {$_ -match ‘\w’}
  
   $clnstring  = -join $ca
   Write-Verbose -Message “Clean string: $clnstring”

  [array]::Reverse($ca)

  $revstring = -join $ca
   Write-Verbose -Message “Reversed string: $revstring”

  ## make test case insensitive
   if ($revstring -ieq $clnstring){
     $true
   }
   else {
     $false
   }

}

There isn’t a method on the string class to reverse a string so convert the string to an array of chars then use Where-object to filter out non-word characters e.g. punctuation. Recreate the input string without the punctuation etc then use the Reverse static method on the array class. Use –join to create the reversed string from the char array.

Use –ieq (force case insensitive comparison) to test if the two strings are equal and return true or false accordingly.

Some simple examples:

PS> test-palindrome -teststring radar
True

PS> test-palindrome -teststring Radar
True

PS> test-palindrome -teststring Richard
False

And testing a phrase:

PS> test-palindrome -teststring “Madam, I’m Adam” -Verbose
VERBOSE: Input string: Madam, I’m Adam
VERBOSE: Clean string: MadamImAdam
VERBOSE: Reversed string: madAmImadaM
True

PS> test-palindrome -teststring ‘The fat cat sat on the mat’
False

This entry was posted in Powershell. Bookmark the permalink.

4 Responses to Test if a string is a palindrome

  1. Glenn Carr says:

    Couldn’t the return value be shortened to simply:
    ($revstring -ieq $clnstring)

  2. Andrey Voronin says:

    -eq IS case insensitive
    You need -ceq for case sensitivity…

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s