Detect if a String is a Palindrome

This one was given to me by PushPay, an awesome company in Redmond. Had never heard of a palindrome. When I started looking it up the ex slapped me upside the head and said "Duh, it's a word, phrase, or sequence that reads the same backward as forward." :s

Back to Code Samples

public static bool IsPalindrome(this string sourceString)
{
if (string.IsNullOrWhiteSpace(sourceString))
{
return false;
}

var startIndex = 0;
var endIndex = sourceString.Length - 1;

// Special case. If the string is all non-chars, it's not a palindrome.
int charMatchCount = 0;

while (startIndex <= endIndex)
{
if (!char.IsLetter(sourceString[startIndex]))
{
startIndex++;
continue;
}

if (!char.IsLetter(sourceString[endIndex]))
{
endIndex--;
continue;
}

if (char.ToUpper(sourceString[startIndex]) != char.ToUpper(sourceString[endIndex]))
{
return false;
}

charMatchCount++;
startIndex++;
endIndex--;
}

return charMatchCount > 1;
}

Back to Code Samples