65.9K
CodeProject is changing. Read more.
Home

To check string is palindrome or not in .NET (C#)

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.60/5 (5 votes)

Mar 8, 2011

CPOL
viewsIcon

13137

downloadIcon

3

You forgot about the non-alphabetic characters in a palindrome.A string like "Madam, in Eden I'm Adam" will produce False in your code, but it is a palindrome!Provide you my version. I also put it in extension method:public static class StringExtension{ public static bool...

You forgot about the non-alphabetic characters in a palindrome. A string like "Madam, in Eden I'm Adam" will produce False in your code, but it is a palindrome! Provide you my version. I also put it in extension method:
public static class StringExtension
{
    public static bool IsPalindrome(this string StrToCheck)
    {
        var lwr = StrToCheck.ToLower().Where(c => char.IsLetter(c));
        return lwr.SequenceEqual(lwr.Reverse());
    }
}
And example:
static void Main(string[] args)
{
    string str1 = "test string", str2 = "Madam, in Eden I'm Adam";
    Console.WriteLine(str1.IsPalindrome());
    Console.WriteLine(str2.IsPalindrome());
}
produces as expected False for str1 and True for str2. P.S.: The method will only fail on input strings that contain no alphabetic characters (such as ",,. .;...."), and return value will be True. You can add code to check lwr.Count() for 0.