Palindromes are strings that if read in both directions will be the same.
Eg:- Malayalam, Civic
In this C# coding example, we will check whether a given string is Palindrome or not using C# language. So, how can we check whether a string is a palindrome in C# or any other programming language?
There are various ways of checking if a string is Palindrome. The easiest is to reverse the string and compare it with the original string. If both are the same the given string is a palindrome.
Palindrome Check in C#
See the below example, to identify whether the given string is a palindrome
/// <summary>
/// Check whether the string is a Palindrome or not
/// </summary>
public static string IsPalindrome(string s)
{
//Reverse the string
char[] charS = s.ToCharArray();
Array.Reverse(charS);
string sRev = new string(charS);
//compare the string with the reversed string
if (s.CompareTo(sRev) == 0)
return s +" is Palindrome";
else
return s + " is not Palindrome";
}
Palindrome Check in VB.NET
See the below code to identify the given string is a palindrome in VB.NET
''' <summary>
''' Check whether the string is a Palindrome or not
''' </summary>
Public Shared Function IsPalindrome(s As String) As String
'Reverse the string
Dim charS As Char() = s.ToCharArray()
Array.Reverse(charS)
Dim sRev As New String(charS)
'compare the string with the reversed string
If s.CompareTo(sRev) = 0 Then
Return s & Convert.ToString(" is Palindrome")
Else
Return s & Convert.ToString(" is not Palindrome")
End If
End Function
Leave a Reply