简体   繁体   中英

Trouble using Array.Reverse

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;
    }
  }

  }
}

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);
}

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));
    }

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM