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:
- By creating char arrays
- By using string reverse method
NB: There are some other methods also, for now I am sharing these two.
By creating char arrays
- 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;
- }
- }
- By using string reverse method
- 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();
- }
Please download to see the entire program. I hope it helps someone.
Output
Points of Interest
- Palindrome, Arrays, Array Manipulations
History
Thank you for reading.