Check a String is Palindrome
Introduction
This tip covers how we can check a string is palindrome or not.
Background
Now a day you can expect a question in every Interviews that to write a program to check whether a String is palindrome or not. I thought of sharing my methods two find out the same 🙂
Using the Code
We can do it in two ways:
NB: There are some other methods also, for now I am sharing these two.
By creating char arrays
[csharp]
private static bool chkPallindrome(string strVal)
{
try
{
int min = 0;
int max = strVal.Length – 1;
while (true)
{
if (min > max)
return true;
char minChar = strVal[min];
char maxChar = strVal[max];
if (char.ToLower(minChar) != char.ToLower(maxChar))
{
return false;
}
min++;
max–;
}
}
catch (Exception)
{
throw;
}
}
[/csharp]
By using string reverse method
[csharp]
private static void CheckAndDisplay(string strReal)
{
string strRev;
char[] tmpChar = strReal.ToCharArray();
Array.Reverse(tmpChar);
strRev = new string(tmpChar);
if (strReal.Equals(strRev, StringComparison.OrdinalIgnoreCase))
{
Console.WriteLine("The string is pallindrome");
}
else
{
Console.WriteLine("The string is not pallindrome");
}
Console.ReadLine();
}
[/csharp]
Please download to see the entire program. I hope it helps someone.
Points of Interest
Palindrome, Arrays, Array Manipulations
History
1st version: 16-11-2014
Thank you for reading.