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:

  1. By creating char arrays

  2. By using string reverse method

    NB: There are some other methods also, for now I am sharing these two.

By creating char arrays

  1. private static bool chkPallindrome(string strVal)  
  2. {  
  3.      try  
  4.      {  
  5.           int min = 0;  
  6.           int max = strVal.Length - 1;  
  7.           while (true)  
  8.           {  
  9.                if (min > max)  
  10.                return true;  
  11.                char minChar = strVal[min];  
  12.                char maxChar = strVal[max];  
  13.                if (char.ToLower(minChar) != char.ToLower(maxChar))  
  14.                {  
  15.                     return false;  
  16.                }  
  17.                min++;  
  18.                max--;  
  19.          }  
  20.      }  
  21.      catch (Exception)  
  22.      {  
  23.           throw;  
  24.      }  
  25. }  
  26. By using string reverse method  
  27. private static void CheckAndDisplay(string strReal)  
  28. {  
  29.      string strRev;  
  30.      char[] tmpChar = strReal.ToCharArray();  
  31.      Array.Reverse(tmpChar);  
  32.      strRev = new string(tmpChar);  
  33.      if (strReal.Equals(strRev, StringComparison.OrdinalIgnoreCase))  
  34.      {  
  35.           Console.WriteLine("The string is pallindrome");  
  36.      }  
  37.      else  
  38.      {  
  39.            Console.WriteLine("The string is not pallindrome");  
  40.      }  
  41.      Console.ReadLine();  
  42. }  
Please download to see the entire program. I hope it helps someone.

Output

output

Points of Interest

 

  • Palindrome, Arrays, Array Manipulations

History

  • 1st version: 16-11-2014
Thank you for reading.