Follow @RoyOsherove on Twitter

Finding a Palindrome

[Update: I added a third variation of this which solves all the problems mentioned in the comments. Was really fun - used a single line of regular expressions and it worked like a charm!]
 
It got me intrigued - so here's my answer to finding a palindrome (a string you can read forward and backward the same):
 

[Test]

   public void TestPelindromSimple()

   {

         Assert.IsTrue(IsPalindrome("a"),"a");

         Assert.IsFalse(IsPalindrome("ab"),"ab");

         Assert.IsTrue(IsPalindrome("aba"),"aba");

         Assert.IsFalse(IsPalindrome("abc"),"abc");

 

         Assert.IsTrue(IsPalindrome("abba"),"abba");

         Assert.IsFalse(IsPalindrome("abbc"),"abbc");

 

         Assert.IsTrue(IsPalindrome("abcba"),"abcba");

         Assert.IsFalse(IsPalindrome("abcbc"),"abcbc");

 

         Assert.IsTrue(IsPalindrome("lelelel"),"lelelel");

         Assert.IsFalse(IsPalindrome("lele4el"),"lele4el");

 

         Assert.IsFalse(IsPalindrome(null),"null");

         Assert.IsTrue(IsPalindrome("ABba"),"ABba");

 

   }

 

 

 

   private bool IsPalindrome(string text)

   {

         if(text==null)

         {

               return false;

         }

         if(text.Length==1)

         {

               return true;

         }

 

         text=text.ToLower();

         int firsthalfIndex = (text.Length/2);

         int secondHalfIndex= (text.Length/2);

 

         if(text.Length%2!=0)

         {

               secondHalfIndex+=1;

         }

         char[] part1 = text.Substring(0,firsthalfIndex).ToCharArray();

         char[] part2 = text.Substring(secondHalfIndex).ToCharArray();

         Array.Reverse(part2);

              

         return (new string( part1)== new string(part2));

   }

 

I liked what I had but then it occurred to me: all these test can pass with this simple routine:

private bool IsPalindrome(string text)

 {

   if(text==null)

   {

      return false;

   }

  

   text=text.ToLower();

   char[] backwards = text.ToCharArray();

   Array.Reverse(backwards);

          

   return (new string( backwards)== text);

 }

 

 

Ain't life funny?

 

[Update]

This variation adds a single line of regex to comply with the dictionary form of Palindrome.

I also added a couple of unit tests to make sure it works:

 

Assert.IsTrue(IsPalindrome("ab cb a"),"ab cb a");

Assert.IsTrue(IsPalindrome("A man, a plan, a canal, Panama!"),"A man, a plan, a canal, Panama!");

 

private bool IsPalindrome(string text)

{

   if(text==null){

      return false;

   }

 

  text=text.ToLower();

  //remove whitespace and other non numeric chars

  text = Regex.Replace(text,@"[\s\W]",string.Empty);

  char[] backwards = text.ToCharArray();

  Array.Reverse(backwards);

                       

  return (new string( backwards)== text);

}

 

No Fun Intended

Israeli .Net Architects meeting - Refactoring, Class designer and other cool stuff in VS.Net 2005