Palindrome in C#

Given a string, check whether the string is a palindrome using C#. Palindromes are words that read the same backward and forward, e.g. level.

Use reversed value

For this solution, the first step is to reverse the input string, then compare the reversed and original string. You might read about string reversal techniques here.

If the string is a palindrome, the reversed form should be equal to the original form. Moreover, we can use StringComparison.InvariantCultureIgnoreCase for an overload of the Equals() method to perform a case-insensitive comparison.

using System.Text;

 public static bool IsPalindrome(string str)
 {
     var reversed = new StringBuilder();
     for (var i = str.Length - 1; i >= 0; i--)
     {
         reversed.Append(str[i]);
     }
     return str.Equals(reversed.ToString(), StringComparison.InvariantCultureIgnoreCase);
 }
While Loop

We can simultaneously iterating the string forward and backward using while loop. If the characters are different, the loop returns false; otherwise, the loop continues. Note that we can use char.ToLower() method to compare the lowered versions of all the characters. It is possible to lowercase the input string with string.ToLower() method. This method returns a copy of the input string converted to lowercase and requires an allocation. However, the char.ToLower() converts the value of a character to its lowercase equivalent.

public static bool IsPalindrome(string str)
{
    var forward = 0;
    var backward = str.Length - 1;
    while (backward > forward)
    {
        if (char.ToLower(str[forward]) != char.ToLower(str[backward])) return false;
        forward++;
        backward--;
    }

    return true;
}
LINQ Operators

Let's take a look at another way of solving the palindrome problem. For this implementation, we are not going to manually reverse any string. Instead, we are going to make use of LINQ extension methods, although this is not an ideal solution for this problem. The Where() method filters output elements that match a given predicate. An overload of Where() provides the positional index of the input element for use in the predicate. The Any() method returns true if the input sequence contains at least one element.

using System.Linq;

 public static bool IsPalindrome(string str)
 {
     return !str.Where((c, i) => char.ToLower(c) != char.ToLower(str[str.Length - i - 1])).Any();
 }

You can download the source code on Github.