Search code examples
c#palindrome

In C#, How can I determine if a given string is a palindrome or not?


I'm currently wondering if when a given string (word), how can I determine if it is a palindrome or not. A palindrome is a word or phrase that is the same if read forward or backward. I think I can solve this by looping through the half the word and comparing each letter with the other half. An example for this could be: (word[0] == word[word.Length-1-0]) would compare the first letter with the last letter of word, and (word[1] == word[word.Length-1-1]) would compare the second letter with the second to last letter.

  • Example Input could be: racecar

  • Example Output: True

Am I approaching this problem correctly towards the proper solution?

Here's a bit of I've written down so far.

public bool Test6(string word)
        {
            for (int i = 0; i < word.Length; i++)
            {
                if (word[0] == word[word.Length - 1 - 0])
                {

                }

Solution

  • Please follow this link http://www.dotnetperls.com/palindrome

    You can do it using this example without using any built in method :

    using System;
    
    class Program
    {
        public static bool IsPalindrome(string value)
        {
        int min = 0;
        int max = value.Length - 1;
        while (true)
        {
            if (min > max)
            {
            return true;
            }
            char a = value[min];
            char b = value[max];
            if (char.ToLower(a) != char.ToLower(b))
            {
            return false;
            }
            min++;
            max--;
        }
        }
    
        static void Main()
        {
        string[] array =
        {
            "civic",
            "deified",
            "deleveled",
            "devoved",
            "dewed",
            "Hannah",
            "kayak",
            "level",
            "madam",
            "racecar",
            "radar",
            "redder",
            "refer",
            "repaper",
            "reviver",
            "rotator",
            "rotor",
            "sagas",
            "solos",
            "sexes",
            "stats",
            "tenet",
    
            "Dot",
            "Net",
            "Perls",
            "Is",
            "Not",
            "A",
            "Palindrome",
            ""
        };
    
        foreach (string value in array)
        {
            Console.WriteLine("{0} = {1}", value, IsPalindrome(value));
        }
        }
    }