Click here to Skip to main content
15,881,559 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I've made a simple program that uses a character array to compare a string to see if it's a palindrome or not but when I use the Array.Reverse method to reverse the second array both of them end up reversing.

C#
Console.Write("> Enter a word or sentence\n> ");
input = Console.ReadLine();
input = input.Replace(" ","");
charArray = input.ToCharArray();
reversedCharArray = charArray;
Array.Reverse(reversedCharArray);


I've fixed the problem by using
C#
reversedCharArray = charArray.Reverse().ToArray();

But I'm curious as to why it didn't work the other way.


The other problem that I'm facing is that
C#
if(charArray == reversedCharArray)

Is always returning false even when the arrays are the same (I've checked the values of the arrays during output) The other way I can see to do this is to output to a string and compare them but that seems like an unnecessary step...
Posted

Look at the line that says reversedCharArray = charArray. You did not make a copy of the array by executing this line. What you did was a second variable point to the same array instance as charArray. You now have two variables pointing to the exact same array instance, charArray and reversedCharArray. What you do using one variable will be reflected by the other.

As for the other question, you cannot compare two arrays like that. You're comparing the references of the arrays. What you're saying is "are these two addresses the same?" If you want to compare them without iterating over the contents of the arrays, element by element, you can convert the reversed array back to a string, then compare the strings.

Here's a little function to reverse a string:
VB
Function ReverseString(target As String) As String
    Dim chars() As Char = target.ToCharArray()
    Array.Reverse(chars)
    Return New String(chars)
End Function
 
Share this answer
 
Your assignment to reversedCharArray created a pointer to charArray. In the example below, I used the CopyTo method to create a copy of the charArray.


C#
string input;
char [] charArray;
char [] reversedCharArray;
Console.Write("> Enter a word or sentence\n> ");
input = Console.ReadLine();
input = input.Replace(" ", "");
charArray = input.ToCharArray();
reversedCharArray = new char[charArray.GetLength(0)];
charArray.CopyTo(reversedCharArray,0);
Array.Reverse(reversedCharArray);
Console.WriteLine(charArray);
Console.WriteLine(reversedCharArray);
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900