Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to create Palindrome with Reverse method

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading