Monthly Archive

Categories

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

Comments are closed.