C# Code Examples

Check if a String is Palindrome in C#?

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
Rajeev

Recent Posts

OWIN Authentication in .NET Core

OWIN (Open Web Interface for .NET) is an interface between web servers and web applications…

1 year ago

Serializing and Deserializing JSON using Jsonconvertor in C#

JSON (JavaScript Object Notation) is a commonly used data exchange format that facilitates data exchange…

1 year ago

What is CAP Theorem? | What is Brewer’s Theorem?

The CAP theorem is also known as Brewer's theorem. What is CAP Theorem? CAP theorem…

1 year ago

SOLID -Basic Software Design Principles

Some of the Key factors that need to consider while architecting or designing a software…

1 year ago

What is Interface Segregation Principle (ISP) in SOLID Design Principles?

The Interface Segregation Principle (ISP) is one of the SOLID principles of object-oriented design. The…

1 year ago

What is Single Responsibility Principle (SRP) in SOLID Design Priciples?

The Single Responsibility Principle (SRP), also known as the Singularity Principle, is a software design…

1 year ago