-1

I need to create a IsPalindrome function where it will determine if a provided string is a palindrome. Alphanumeric chars will be considered when evaluating whether or not the string is a palindrome. With this said, I am having trouble trying to disreguard the spaces and the Caps. Here is what my function looks like now. If this makes a difference: After this function is done I will then have to have parse a JSON file and have each element in the "strings" array, into the IsPalindrome function. Any tips?

 private static bool IsPalindrome(string value)
    {
        var min = 0;
        var max = value.Length - 1;

        while (true)
        {
            if (min > max)
                return true;
            var a = value[min];
            var b = value[max];

            if (if (char.ToLower(a) == char.ToLower(b))
             {
              return true;
             }
              else {
                 return false;
              }

            min++;
            max--;
        }
idkidk
  • 61
  • 5
  • Consider using a `for` loop instead of a `while` loop, as it might make it easier to reason about. – Dai Jan 04 '20 at 03:46

1 Answers1

0

The way I'd do this is to turn the string into an array of characters, skipping non-letter characters, and making all the characters lowercase. Then, I'd use an index to check if the first half of the array is equal to the last. Something like this:

public static bool IsPalindrome(string value)
{
    char[] forwards = (from c in value.ToLower().ToCharArray() where char.IsLetter(c) select c).ToArray();
    int middle = (forwards.Length / 2) + 1;
    for (int i = 0; i < middle; i++)
        if (forwards[i] != forwards[forwards.Length - 1 - i])
            return false;
    return true;
}

That first line uses LINQ to make the array, so you need a using System.Linq;

jgfооt
  • 914
  • 6
  • 12
  • There are plenty of answers like this already... Except most don't incorrectly claim that you need to turn string into char array in order to iterate over characters of string... Instead you could've explained what OP did wrong for example.. – Alexei Levenkov Jan 04 '20 at 06:05