Checking if a string is a palindrome

Back in my original college days (over 20 years ago now) this used to be the subject of a running joke. It seemed that with every new language learned one of the first exercises was to check for palindromes, and the joke was that we couldn't wait to get into gainful employment with some large corporation, hopefully working with their Palindrome product group - as we had so much experience!.

So what's a palindrome? Wikipedia explains it as "a word, phrase, number, or other sequence of symbols or elements, whose meaning may be interpreted the same way in either forward or reverse direction". So we're basically checking if the string can be reversed and still have the same letter order. In .Net we could use String.Reverse() and work on the resulting list, but doing it the old fashioned way I get code like this

  char[] checkChars = testString.ToCharArray();
 
 for (int i = 0; i < checkChars.Length / 2; i++)
 {
 if (checkChars[i] != checkChars[checkChars.Length - i - 1])
 {
 return false;
 }
 }
 return true;

 

But that method would fail on some common palindromic strings like "Navan" (casing) or "A man a plan a canal panama" (casing and spaces). So in the full version I ignore casing and spaces to get an implementation like:

  private static bool IsPalindrome(string testString)
 {
 StringBuilder checkChars = new StringBuilder();
 
 foreach (char c in testString.ToLower())
 {
 if (c != ' ')
 {
 checkChars.Append(c);
 }
 }
 
 for (int i = 0; i < checkChars.Length / 2; i++)
 {
 if (checkChars[i] != checkChars[checkChars.Length - i - 1])
 {
 return false;
 }
 }
 return true;
 }

Comments

  • Anonymous
    November 07, 2013
    Very good, easy to get blinkered focusing on the letters and not the potential whitespace differences that ultimately would return you "false". That said, is a string with spaces really a palindrome?