To check string is palindrome or not in .NET (C#)
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 string
s that contain no alphabetic characters (such as ",,. .;...."
), and return value will be True
. You can add code to check lwr.Count()
for 0
.