Saturday, June 14, 2014

Widgets

Program in C#: How to Check if a String is Palindrome or not - Three line solution - Shortest Method

Today i will tell you program in C#, about how to check whether a string is a Palindrome or not. You may also check Long version.

What is Palindrome?

Palindrome is a word, phrase, number, or other sequence of symbols or elements that reads the same forward or reversed. For example: "madam", "1221". 

For this program you just need to Create a Console Application. And add this code to Main() method. Main is the method which is called first in Console Application in C#.

Here's the code:


 string phrase=Console.ReadLine();
 Console.WriteLine(Enumerable.SequenceEqual(phrase, phrase.Reverse()));
 Console.ReadLine();
What happened in this code?
We first declare a string 
phrase  value of which we read from the user input. Then we write the result of :

 Enumerable.SequenceEqual(phrase, phrase.Reverse());
 
Now, Enumerable Sequence returns true if the two source sequences are of equal length and their corresponding elements are equal according to the default equality comparer for their type. Which in simpler form means if both strings are same then the result is true else it is false. Now since a string is a palindrome if it is same if read reversed, therefore phrase.Reverse() reverese the phrase string and Enumerable.SequenceEqual(phrase, phrase.Reverse()) compares both strings.
Output:
Output is True for Palindrome String "civic"


Output is False for Non Palindrome String "hello"
Please share this post if you find it useful.

No comments:

Post a Comment