Saturday, June 10, 2017

C# - Check if a given string is Palindrome or not

In this article, we will write a program in C# which checks if the given string is a palindrome or not.

Question - What is palindrome?

Answer- A palindrome could be a word, phrase, or sequence that reads the same backwards as forwards, e.g. MADAM

class Program
    {
        static void Main(string[] args)
        {
            #region palindrome check

            Console.WriteLine("Enter a string to know if it is palindrome");
            string strPalindrome = Console.ReadLine();
            Console.WriteLine(CheckPalindrome(strPalindrome));
            Console.ReadKey();

            #endregion
         }
       
        #region Method To check a given string is palindrome or not

        private static string CheckPalindrome(string str)
        {
            string plndrmStr = string.Empty;
            string msg = string.Empty;

            #region OneWay
            // In this particular way, we will reverse the given string and store it into another string.
            // Now we will compare both the strings and check if the string is palindrome or not.

            for (int i = str.Length - 1; i != -1; i--)
            {
                plndrmStr += str[i];
            }
            if (str == plndrmStr)
            {
                msg = "Given String is Palindrome.";
            }
            else { msg = "Given String is not Palindrome."; }

            #endregion

            #region SecondWay
           // In this particular way, we will not be having another string to compare to the original one.
           // we are taking single FOR loop which proceeds forward and backward and checks if the //characters are equals

            for (int i = 0, j = str.Length - 1; i <= j && j != -1; i++, j--)
            {
                if (str[i] == str[j])
                {
                    msg = "Given String is Palindrome.";
                }
                else
                { msg = "Given String is not Palindrome."; break; }
            }

            #endregion

            return msg;
        }

        #endregion

    }
}

CONSOLE OUTPUT(s):

Enter a string to know if it is palindrome
MAN
Given String is not Palindrome.

Enter a string to know if it is palindrome
SOS
Given String is Palindrome.

No comments:

Post a Comment

SQL INTERVIEW QUESTIONS (SCENARIO BASED) - Part 1

FINDING Second Highest Salary in SQL CREATE TABLE #EMP ( NAME NVARCHAR ( 100 ), SALARY BIGINT ) INSERT INTO #EMP VALUES (...