[SOLVED] How to create Palindrome with Reverse method

Issue

I am learning C# but I just stack at some simple task with creating Palindrome function. I decided to change string to char array and then use reverse method and compare initial char array to reversed one. But it is look like reverse method do not work when put into if statement, or maybe I made mistake somewhere else??

void IsPalindrome(string x)
{
    bool isEqual = true;

    char[] charArr = x.ToCharArray();
    char[] reversed = charArr;


    Array.Reverse(reversed);
    for (int i = 0; i < reversed.Length; i++)
    {

        if (reversed[i] != charArr[i])
        {
            isEqual = false;
        }
    }

    if (isEqual == true)
    {
        Console.WriteLine($"True, {x.Length}");
    }
    else
    {
        Console.WriteLine($"False, {x.Length}");
    }
  
}

Console.WriteLine("Type a string:");
string? userString = Console.ReadLine();

IsPalindrome(userString);

Solution

charArr and reversed are pointing to the same address in memory. Try this instead:

void IsPalindrome(string x)
{
    bool isEqual = true;

    char[] reversed = x.ToCharArray();

    Array.Reverse(reversed);
    for (int i = 0; i < reversed.Length; i++)
    {

        if (reversed[i] != x[i])
        {
            isEqual = false;
        }
    }

    if (isEqual == true)
    {
        Console.WriteLine($"True, {x.Length}");
    }
    else
    {
        Console.WriteLine($"False, {x.Length}");
    }
  
}

Console.WriteLine("Type a string:");
string? userString = Console.ReadLine();

IsPalindrome(userString);

Answered By – Peter Mourfield

Answer Checked By – Dawn Plyler (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.