0

I am new to programming, particularly in C#, and I thought I'd start with something simple like a text reverser. I thought I'd take it a little further and also make it a Palindrome checker. The problem is I can't seem to convert the array back into a string to check it to the original input.

string Inp = "1";  // user input

Console.WriteLine("Input a word to reverse"); // user inputs word
Inp = Convert.ToString(Console.ReadLine()); // input gets converted to string

char[] charArray = Inp.ToCharArray(); // converts char to array
Array.Reverse(charArray); // reverses array

if (Inp == charArray) { // compares user input to the array - does not work
    Console.WriteLine(Inp + " is a Palindrome"); // writes the input with text afterwards
} else {
    Console.WriteLine(Inp + " is not a palindrome");
}

I have tried things like Convert.ToString and other versions of that but it didn't seem to work. I tried creating new string = (charArray) to create a new string bur that didn't work either. Thank you.

EDIT: It gives me this error:

Operator '==' cannot be applied to operands of type 'string' and 'char[]'

Also, a little unrelated, but are there too many annotations? Should I do less? And did I ask the question correctly or is there something I did wrong and missed out?

1
  • if (Inp.SequenceEqual(charArray)) { // Palindrome } else { // no Palindrome } , Btw, you don't need to convert a string to string. Commented Jan 30, 2021 at 6:28

1 Answer 1

4

I don't understand what your problem is, this just works:

Code:

using System;

namespace ConsoleApp1
{
    internal static class Program
    {
        private static void Main()
        {
            var chars = new[] {'a', 'b', 'c'};
            var s = new string(chars);
            Console.WriteLine(s);
        }
    }
}

Result:

abc

For your comparison problem, here's a more robust way on how to do it:

using System;

namespace ConsoleApp1
{
    internal static class Program
    {
        private static void Main()
        {
            var sourceChars = new[] {'a', 'b', 'c'};
            var targetChars = new[] {'C', 'B', 'A'};

            Array.Reverse(sourceChars);

            var sourceString = new string(sourceChars);
            var targetString = new string(targetChars);

            var isMatch = string.Equals(sourceString, targetString, StringComparison.OrdinalIgnoreCase);

            Console.WriteLine(isMatch);
        }
    }
}

Result:

True

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.