Hello everyone,

I need to create a program that checks to see if a word or phrase is a palindrome. A palindrome if you are not familiar is a word or phrase that reads the same forwards and backwards like racecar, disregarding punctuation, case, and spaces (basically, any non-alphabetic characters.

I need to create a method that strips out non-alphabetic characters, and another Boolean-valued method that returns the value True when the word or phrase is a palindrome and the value False otherwise.

I am totally lost if anyone could please help. Just fyi I am using visual studios 2013 C#.

How about this:

using System;
using System.Linq;

namespace Palindrome
    public class Program
        static void Main(string[] args)
            Console.WriteLine("racecar: " + "racecar".IsPalindrome());
            Console.WriteLine("dad: " + "dad".IsPalindrome());
            Console.WriteLine("mum: " + "mum".IsPalindrome());
            Console.WriteLine("dog: " + "dog".IsPalindrome());
            Console.WriteLine("floor: " + "floor".IsPalindrome());
            Console.WriteLine("Racecar: " + "Racecar".IsPalindrome());
            Console.WriteLine("Rac ecar: " + "Rac ecar".IsPalindrome());
            Console.WriteLine("Racecar': " + "Racecar'".IsPalindrome());


    public static class StringExtensions
        public static bool IsPalindrome(this string word)
            var lettersOnly = String.Join("", word.ToLower().Where(Char.IsLetter));

            var reversedWord = String.Join("", lettersOnly.Reverse());

            return lettersOnly == reversedWord;        
Great LINQ!

Dave, I just have one question, why does Char.IsLetter work? Should this not be Char.IsLetter(ch)? Or is this implied by LINQ?


Sorry for the late replay, out all day yesterday.

The compact shorthand I have used here is called a Method Group.

To really understand this I would type for about 10 pages or if you have time watch these videos in this order. Will take a while but they are really high quality and very enjoyable.






Finally consider the following progression - think of that image of an ape gradually evolving into a human!

//var lettersOnly = String.Join("", word.ToLower().Where(delegate(char c) { return Char.IsLetter(c); }));
//var lettersOnly = String.Join("", word.ToLower().Where((char c) => { return Char.IsLetter(c); }));
//var lettersOnly = String.Join("", word.ToLower().Where(c => { return Char.IsLetter(c); }));
//var lettersOnly = String.Join("", word.ToLower().Where(c => Char.IsLetter(c)));
var lettersOnly = String.Join("", word.ToLower().Where(Char.IsLetter));

Edited 1 Year Ago by DaveAmour

Gee man, again great stuff!

Thanks for de good quality videos!
Love your comparision of the ape evolution!
Little remark: I hope you know that apes and man had a common ancestor.
A chimp will never evolve into a human. :)

This article has been dead for over six months. Start a new discussion instead.