Check Palindrome String in C#
To check Palindrome string in C# there are many ways:1. Using string Reverse() method
2. Using Array.Reverse() method
1. Using string Reverse() method
Using String Reverse you can checkSequenceEqual()
.Example
using System;
using System.Linq;
public class Program
{
public static void Main()
{
string stringToTest = "level";
bool isPalindrome = stringToTest.SequenceEqual(stringToTest.Reverse());
Console.WriteLine("Is {0} palindrome: {1}", stringToTest, isPalindrome);
string anotherStringToTest = "levels";
bool isNotPalindrome = anotherStringToTest.SequenceEqual(anotherStringToTest.Reverse());
Console.WriteLine("Is {0} palindrome: {1}", anotherStringToTest, isNotPalindrome);
}
}
Output
Is level palindrome: True
Is levels palindrome: False
Is levels palindrome: False
2. Using Array.Reverse() method
First you create an Array of chars usingToCharArray()
Method, then you copy this array into another using CopyTo()
method, then you reverse new array using Array.Reverse()
, Finally you check if original array and reversed array using Enumerable.SequenceEqual()
.Example
using System;
using System.Linq;
using System.Collections;
public class Program
{
public static void Main()
{
string stringToTest = "level";
char[] stringToArray = stringToTest.ToCharArray();
var reversedArray = new char[stringToArray.Length];
stringToArray.CopyTo(reversedArray, 0);
Array.Reverse(reversedArray);
bool isEqual = Enumerable.SequenceEqual(stringToArray, reversedArray);
Console.WriteLine("Is {0} palindrome: {1}",stringToTest, isEqual);
}
}
Output
Is level palindrome: True