CSharp - Write program to check whether a string is a palindrome or not without reversing the string

Requirements

Write program to check whether a string is a palindrome or not without reversing the string

Hint

We will start with the middle position of the string and then proceed.

We can have a palindrome of even length (e.g., abccba), or we can have a palindrome string of odd length (e.g., abcdcba).

We need to take care of both scenarios.

Demo

using System;

public class MainClass
{
    public static void Main(String[] argv)
    {// w  ww.ja  v  a 2 s. c  o  m
        Console.WriteLine("Enter the string:");
        string test = Console.ReadLine();
        char[] testForPalindrome = test.ToCharArray();
        int len = testForPalindrome.Length;
        int mid = len / 2;
        bool flag = true;
        //odd palindrome
        if (len % 2 != 0)
        {
            int j = mid + 1;
            for (int i = mid - 1; i >= 0; i--)
            {
                if (testForPalindrome[i] != testForPalindrome[j])
                {
                    flag = false;
                }
                j++;
            }
            Console.WriteLine("The string {0} is palindrome? {1}", test, flag);
        }
        //even palindrome
        else
        {
            int j = mid;
            for (int i = mid - 1; i >= 0; i--)
            {
                if (testForPalindrome[i] != testForPalindrome[j])
                {
                    flag = false;
                }
                j++;
            }
            Console.WriteLine("The string {0} is palindrome? {1}", test, flag);
        }
    }
}

Result