Search code examples
c#arrayspalindrome

Converting a fully lower case / uper case char array back to the user input


I made a palindrome program on c#. To remove case sensitivity I had to convert the input into lower (or upper) case completely. Now when I am printing the reverse array, I want the case sensitivity to come back. Such as if input = Madam, I want Reverse to be = madaM. Now I know I can make a new char array from the input and I've already done that. But I want to manipulate the LowerInvariant array somehow. I know the Upper method of my code doesn't work because the array is converted into lower case.

using System;
using System.Linq;

public class Palindrome
 {
   public static void Main(string [] args)
   {
      string input = Console.ReadLine();
      string lower = input.ToLowerInvariant();
      char[] array = lower.ToCharArray();
      Array.Reverse(array);
      Upper(array, input);
      Console.WriteLine("\nPalindrome: {0}", array.SequenceEqual(lower));
      Console.ReadKey();
   }

   public static void Upper(char[] array, string input)
   {
      for (int i = 0; i < array.Length; i++)
      {
         if (Input's [i] char is Upper) => Not sure how to put this as a code.
            array[i] = Char.ToUpper(array[i]);
      }

      Console.WriteLine("Reverse array :");
      for (int i = 0; i < array.Length; i++)
         Console.Write("{0}", array[i]);
   }
}

Solution

  • This should do what you want:

    public static void Upper(char[] array, string input)
    {
        Console.WriteLine("Reverse array :");
        Console.Write(new string(input.AsEnumerable().Reverse().ToArray()));
    }
    

    Rather than worrying about the lowercased array, you can simply reverse the original input and make a new string out of the reversed characters.