Click here to Skip to main content
15,867,141 members
Articles / Programming Languages / C#
Alternative
Tip/Trick

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

Rate me:
Please Sign up or sign in to vote.
4.60/5 (5 votes)
8 Mar 2011CPOL 12.6K   1   2
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:
C#
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:
C#
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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer DevelopEx
Ukraine Ukraine
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralReason for my vote of 5 You were the only one to raise an in... Pin
YvesDaoust23-Jan-12 21:01
YvesDaoust23-Jan-12 21:01 
GeneralWho said that the empty string is not a palindrome ? ;) Pin
YvesDaoust23-Jan-12 21:00
YvesDaoust23-Jan-12 21:00 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.