C# Coding challenge - Check for palindrome

Check for palindrome

I decided to blog about some problems and how I solved them. Today is checking if a word is a palindrome. The definition of a palindrome is "a word, phrase, or sequence that reads the same backward as forward".

To do this I made a little extension method for a string called IsPalindrome.

public static class PalindromeChecker
{
    public static bool IsPalindrome(this string word)
    {
        var reversedWord = word.Reverse();

        var same = true;
        for (var i = 0; i < reversedWord.Count(); i++)
        {
            if (word[i] == reversedWord.ElementAt(i)) continue;
            same = false;
        }
        return same;
    }
}

It is a fairly simple method that uses the string Reverse method.
And I wrote some tests to know if it actually works or not.

[TestMethod]
public void racecar_ShouldBePalindrome()
{
    var word = "racecar";
    var isPalindrome = word.IsPalindrome();

    Assert.IsTrue(isPalindrome);
}

[TestMethod]
public void Car_ShouldNotBePalindrome()
{
    var word = "car";
    var isPalindrome = word.IsPalindrome();

    Assert.IsFalse(isPalindrome);
}

I'm sure there are other ways to solve this as well. If you have a better way I would be glad for you to share it with me.

Jeffery Weiler

I'm a .Net developer working with C# doing desktop applications with winforms and wpf. If you enjoy what you are reading subscrbe here. http://www.jweiler.com/subscribe/

Read More
C# Coding challenge - Check for palindrome
Share this