Reputation: 29
I am writing code to check for symmetry within a string. I convert to a Char array and then I would like to use the Array.Reverse method. I keep getting a cannot convert type void to Char[]. Any insight would be greatly appreciated my code is as follows.
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
checkPalindrome("aabaa");
}
public static bool checkPalindrome(string inputString)
{
char[] charArray = inputString.ToCharArray();
char[] reverseArray = Array.Reverse(charArray);
Array.Reverse(charArray);
//Console.Write(charArray);
//Console.Write(reverseArray);
if (charArray = Array.Reverse(charArray))
{
return true;
}
else
{
return false;
}
}
}
}
Upvotes: 0
Views: 1065
Reputation: 156524
Your problem is here:
char[] reverseArray = Array.Reverse(charArray);
Array.Reverse changes the contents of the array that you pass it. It doesn't return any value.
You can use LINQ to do something like this instead:
char[] reverseArray = charArray.Reverse().ToArray();
Then, when you're checking for equality, you need to do more than the default object-equals type of equality check:
if (charArray.SequenceEqual(reverseArray))
Also, .ToArray()
is only necessary if you need an array, and you don't need one for SequenceEqual()
. And the if(something) {return true;} else {return false;}
pattern can be simplified to return something;
So the entire method can actually be written in a single line:
public static bool checkPalindrome(string inputString)
{
return inputString.Reverse().SequenceEqual(inputString);
}
Upvotes: 8
Reputation: 942
A better way - no array cloning/array extraction:
static bool checkPalindrome(string inputString)
{
var length = inputString.Length;
var half = length / 2 + 1;
return length <= 1 || inputString.Take(half).SequenceEqual(inputString.Reverse().Take(half));
}
Upvotes: 0
Reputation: 32276
Here's a better way to determine symetry in a string
.
public bool IsSymetric(string str)
{
if(str == null) return true; // or false or throw an exception
for(int i = 0; i < str.Length/2; i++)
{
if(str[i] != str[str.Length - 1 - i])
{
return false;
}
}
return true;
}
Upvotes: 0