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