## Finding a Palindrome

My blog has moved.
You can view this post at the following address:
http://www.osherove.com/blog/2004/9/15/finding-a-palindrome.html
Published Thursday, September 16, 2004 2:01 AM by RoyOsherove
Filed under:

Wednesday, September 15, 2004 11:07 PM by Jonathan Cogley

#### # re: Finding a Palindrome

Nice refactoring! :-)

As a TDDer, expressing the rules with Asserts just makes so much sense - nice to see others think the same!

I have always thought of palindromes as being more loose, such as:

Although I guess this would simply require same-casing everything and removing whitespace and punctuation ...
Thursday, September 16, 2004 12:28 AM by Richard Tallent

#### # re: Finding a Palindrome

private bool IsPalindrome(string text)
{
if(text==null) return false;
text=text.ToLower();
string backwards=Microsoft.VisualBasic.StrReverse(text);
return (backwards==text);
}
Thursday, September 16, 2004 5:16 AM by Ross

#### # re: Finding a Palindrome

"X" == "X" ? Or "X".Equals( "X" ) ?
Thursday, September 16, 2004 2:33 PM by Mani Swaminathan

#### # re: Finding a Palindrome

As per the original algorithm
just modifying a little, i like the idea of going half way than using string operations which are expensive

char[] a = text.ToCharArray();
bool b = true;
int l = a.length;
int i =0;
while ( b && i < l/2 )
{
if ( !(a[i] == a[l-i-1]) ) b=false;
i++;
}
return b;

Saturday, September 18, 2004 11:35 AM by Dan Golick

#### # re: Finding a Palindrome

You should probably get rid of white space first. Generally people don't consider white space in palindromes.
Sunday, September 19, 2004 1:28 PM by Able was I, ere I saw Elba

#### # re: Finding a Palindrome

Mani's solution is good, but why create a character array unnecessarily, and why keep looping when you've established they're different? The string class already has an indexer so you can do:
if (text[i] == test[l-i-1])

You could generalize it to ignore whitespace and punctuation (air code) ...

int firstIndex = 0;
int lastIndex = text.Length-1;
while(firstIndex < lastIndex)
{
// Ignore punctuation and whitespace
if (Char.IsPunctuation(text[firstIndex]) || Char.IsWhiteSpace(text[firstIndex]))
{
firstIndex++;
continue;
}
if (Char.IsPunctuation(text[lastIndex]) || Char.IsWhiteSpace(text[lastIndex]))
{
lastIndex--;
continue;
}
if (Char.ToLower(text[firstIndex]) != Char.ToLower(text[lastIndex])) return false;
firstIndex++;
lastIndex--;
}
return true;