How to check if String is Palindrome using C#?


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!

Updated on: 22-Jun-2020

299 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements