How to check if String is Palindrome using C#?

CsharpProgrammingServer Side Programming

Let’s say we need to find that the following string is Palindrome or not −

str = "Level";

For that, convert the string into character array to chec each character −

char[] ch = str.ToCharArray();

Now find the reverse −

Array.Reverse(ch);

Use the Equals method to find whether the reverse is equal to original array or not −

bool res = str.Equals(rev, StringComparison.OrdinalIgnoreCase);

The following is the complete code −

Example

 Live Demo

using System;
namespace Demo {
   class Program {
      static void Main(string[] args) {

         string str, rev;
         str = "Level";
         char[] ch = str.ToCharArray();
         Array.Reverse(ch);
         rev = new string(ch);
         bool res = str.Equals(rev, StringComparison.OrdinalIgnoreCase);
     
         if (res == true) {
            Console.WriteLine("String " + str + " is a Palindrome!");
         } else {
            Console.WriteLine("String " + str + " is not a Palindrome!");
         }
         Console.Read();
      }
   }
}

Output

String Level is a Palindrome!
raja
Published on 21-Aug-2018 13:52:59
Advertisements