Checking if a string is a palindrome

Checking if a string is a palindrome

Rate This
  • Comments 1

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;
}


 

Blog - Comment List MSDN TechNet
  • Loading...
Leave a Comment
  • Please add 6 and 3 and type the answer here:
  • Post