Click here to Skip to main content
Click here to Skip to main content
Alternative Tip/Trick

Tagged as

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

, 8 Mar 2011 CPOL
Rate this:
Please Sign up or sign in to vote.
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.

License

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

Share

About the Author

intrueder
Software Developer DevelopEx
Ukraine Ukraine
No Biography provided

Comments and Discussions

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

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.141220.1 | Last Updated 8 Mar 2011
Article Copyright 2011 by intrueder
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid