[c#] Check if a string is a palindrome

I have a string as input and have to break the string in two substrings. If the left substring equals the right substring then do some logic.

How can I do this?

Sample:

public bool getStatus(string myString)
{

}

Example: myString = "ankYkna", so if we break it into two substring it would be: left-part = "ank", right-part = "ank" (after reversal).

This question is related to c# string palindrome

The answer is


Since a palindrome also includes numbers, words, sentences, and any combinations of these, and should ignore punctuation and case, (See Wikipedia Article) I propose this solution:

public class Palindrome
{
    static IList<int> Allowed = new List<int> {
        'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'h',
        'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q',
        'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
        '1', '2', '3', '4', '5', '6', '7', '8', '9',
        '0'
    };
    private static int[] GetJustAllowed(string text)
    {
        List<int> characters = new List<int>();
        foreach (var c in text)
             characters.Add(c | 0x20); 

        return characters.Where(c => Allowed.Contains(c)).ToArray();
    }
    public static bool IsPalindrome(string text)
    {
        if(text == null || text.Length == 1)
             return true;

        int[] chars = GetJustAllowed(text);
        var length = chars.Length;

        while (length > 0)
            if (chars[chars.Length - length] != chars[--length])
                return false;

        return true;
    }
    public static bool IsPalindrome(int number)
    {
        return IsPalindrome(number.ToString());
    }
    public static bool IsPalindrome(double number)
    {
        return IsPalindrome(number.ToString());
    }
    public static bool IsPalindrome(decimal number)
    {
        return IsPalindrome(number.ToString());
    }

}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


class palindrome
{
    static void Main(string[] args)
    {
        Console.Write("Enter a number:");
        string panstring = Console.ReadLine();
        Palindrome(panstring);
        Console.ReadKey();
    }
     static int index = 0;
     public static void Palindrome(string strexcluding)
    {
        try
        {
            string reversecounter = string.Empty;

            for (int i = strexcluding.Length - 1; i >= 0; i--)
            {
                if (strexcluding[i].ToString() != null)
                    reversecounter += strexcluding[i].ToString();
            }
            if (reversecounter == strexcluding)
            {
                Console.WriteLine("Palindrome Number: " + strexcluding);
            }
            else
            {
                Sum(strexcluding);
            }
        }
         catch(Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }
    }

    public static void Sum(string stringnumber)
    {
        try
        {
            index++;
            string number1 = stringnumber;
            string number2 = stringnumber;
            string[] array = new string[number1.Length];
            string obtained = string.Empty;
            string sreverse = null;

            Console.WriteLine(index + ".step : " + number1 + "+" + number2);

            for (int i = 0; i < number1.Length; i++)
            {
                int temp1 = Convert.ToInt32(number1[number1.Length - i - 1].ToString());
                int temp2 = Convert.ToInt32(number2[number2.Length - i - 1].ToString());

                if (temp1 + temp2 >= 10)
                {
                    if (number1.Length - 1 == number1.Length - 1 - i)
                    {
                        array[i] = ((temp1 + temp2) - 10).ToString();
                        obtained = "one";
                    }
                    else if (number1.Length - 1 == i)
                    {
                        if (obtained == "one")
                        {
                            array[i] = (temp1 + temp2 + 1).ToString();
                        }
                        else
                        {
                            array[i] = (temp1 + temp2).ToString();
                        }
                    }
                    else
                    {
                        if (obtained == "one")
                        {
                            array[i] = ((temp1 + temp2 + 1) - 10).ToString();
                        }
                        else
                        {
                            array[i] = ((temp1 + temp2) - 10).ToString();
                            obtained = "one";
                        }

                    }
                }

                else
                {
                    if (obtained == "one")
                        array[i] = (temp1 + temp2 + 1).ToString();
                    else
                        array[i] = (temp1 + temp2).ToString();
                    obtained = "Zero";
                }

            }

            for (int i = array.Length - 1; i >= 0; i--)
            {
                if (array[i] != null)
                    sreverse += array[i].ToString();
            }

            Palindrome(sreverse);
        }
        catch(Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }
    }
}

In C# :

public bool EhPalindromo(string text)
{
 var reverseText = string.Join("", text.ToLower().Reverse());
 return reverseText == text;
}

public static bool palindrome(string t)
    {
        int i = t.Length;
        for (int j = 0; j < i / 2; j++)
        {
            if (t[j] == t[i - j-1])
            {
                continue;
            }
            else
            {
                return false;
                break;
            }
        }
        return true;
    }

This way is both concise in appearance & processes very quickly.

Func<string, bool> IsPalindrome = s => s.Reverse().Equals(s);

String extension method, easy to use:

    public static bool IsPalindrome(this string str)
    {
        str = new Regex("[^a-zA-Z]").Replace(str, "").ToLower();
        return !str.Where((t, i) => t != str[str.Length - i - 1]).Any();
    }

A single line of code using Linq

public static bool IsPalindrome(string str)  
{
    return str.SequenceEqual(str.Reverse());
}

Here is an absolutely simple way to do this,

  1. Receive the word as input into a method.
  2. Assign a temp variable to the original value.
  3. Loop through the initial word, and add the last character to the reversal that you are constructing until the inital word has no more characters.
  4. Now use the spare you created to hold the original value to compare to the constructed copy.

This is a nice way as u don't have to cast ints and doubles. U can just pass them to the method in their string representation by using the ToString() method.

public static bool IsPalindrome(string word)
    {
        string spare = word;
        string reversal = null;
        while (word.Length > 0)
        {
            reversal = string.Concat(reversal, word.LastOrDefault());
            word = word.Remove(word.Length - 1);
        }
        return spare.Equals(reversal);
    }

So from your main method, For even and odd length strings u just pass the whole string into the method.


public static  bool IsPalindrome(string word)
        {
            //first reverse the string
            string reversedString = new string(word.Reverse().ToArray());
            return string.Compare(word, reversedString) == 0 ? true : false;
        }

 private void CheckIfPalindrome(string str) 
        {
            //place string in array of chars
            char[] array = str.ToCharArray(); 
            int length = array.Length -1 ;
            Boolean palindrome =true;
            for (int i = 0; i <= length; i++)//go through the array
            {
                if (array[i] != array[length])//compare if the char in the same positions are the same eg "tattarrattat" will compare array[0]=t with array[11] =t if are not the same stop the for loop
                {
                    MessageBox.Show("not");
                    palindrome = false;
                    break;

                }
                else //if they are the same make length smaller by one and do the same 
                {                   
                  length--;
                }

            }
            if (palindrome) MessageBox.Show("Palindrome"); 

        }

public bool IsPalindroom(string input)
{
    input = input.ToLower();
    var loops = input.Length / 2;
    var higherBoundIdx = input.Length - 1;
    for (var lowerBoundIdx = 0; lowerBoundIdx < loops; lowerBoundIdx++, higherBoundIdx--)
    {
        if (input[lowerBoundIdx] != input[higherBoundIdx])
        return false;
    }
    return true;
}

use this way from dotnetperls

  using System;

    class Program
    {
        /// <summary>
        /// Determines whether the string is a palindrome.
        /// </summary>
        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];

                // Scan forward for a while invalid.
                while (!char.IsLetterOrDigit(a))
                {
                    min++;
                    if (min > max)
                    {
                        return true;
                    }
                    a = value[min];
                }

                // Scan backward for b while invalid.
                while (!char.IsLetterOrDigit(b))
                {
                    max--;
                    if (min > max)
                    {
                        return true;
                    }
                    b = value[max];
                }

                if (char.ToLower(a) != char.ToLower(b))
                {
                    return false;
                }
                min++;
                max--;
            }
        }

        static void Main()
        {
            string[] array =
            {
                "A man, a plan, a canal: Panama.",
                "A Toyota. Race fast, safe car. A Toyota.",
                "Cigar? Toss it in a can. It is so tragic.",
                "Dammit, I'm mad!",
                "Delia saw I was ailed.",
                "Desserts, I stressed!",
                "Draw, O coward!",
                "Lepers repel.",
                "Live not on evil.",
                "Lonely Tylenol.",
                "Murder for a jar of red rum.",
                "Never odd or even.",
                "No lemon, no melon.",
                "Senile felines.",
                "So many dynamos!",
                "Step on no pets.",
                "Was it a car or a cat I saw?",

                "Dot Net Perls is not a palindrome.",
                "Why are you reading this?",
                "This article is not useful.",
                "...",
                "...Test"
            };

            foreach (string value in array)
            {
                Console.WriteLine("{0} = {1}", value, IsPalindrome(value));
            }
        }
    }

class Program
{
    static void Main(string[] args)
    {

        string s, revs = "";
        Console.WriteLine(" Enter string");
        s = Console.ReadLine();
        for (int i = s.Length - 1; i >= 0; i--) //String Reverse
        {
            Console.WriteLine(i);
            revs += s[i].ToString();
        }
        if (revs == s) // Checking whether string is palindrome or not
        {
            Console.WriteLine("String is Palindrome");
        }
        else
        {
            Console.WriteLine("String is not Palindrome");
        }
        Console.ReadKey();
    }
}

Shortest technique to find Palindrome using conventional way

public string IsPalindrome(string Word)
{
    int i = 0, j = Word.Length - 1;
    for (; i < Word.Length - 1 && j >= 0 && Word[i] == Word[j]; i++, j--) ;
    return j == 0 ? "Palindrome" : "Not Palindrome";
}

This is a short and efficient way of checking palindrome.

bool checkPalindrome(string inputString) {

    int length = inputString.Length;
    for(int i = 0; i < length/2; i++){
        if(inputString[i] != inputString[length-1-i]){
            return false;
        }
    }

    return true;

}

//This c# method will check for even and odd lengh palindrome string

public static bool IsPalenDrome(string palendromeString)
        {
            bool isPalenDrome = false;

            try
            {
                int halfLength = palendromeString.Length / 2;

                string leftHalfString = palendromeString.Substring(0,halfLength);

                char[] reversedArray = palendromeString.ToCharArray();
                Array.Reverse(reversedArray);
                string reversedString = new string(reversedArray);

                string rightHalfStringReversed = reversedString.Substring(0, halfLength);

                isPalenDrome = leftHalfString == rightHalfStringReversed ? true : false;
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return isPalenDrome;
        }

 public static bool IsPalindrome(string value)
        {
            int i = 0;
            int j = value.Length - 1;
            while (true)
            {
                if (i > j)
                {
                    return true;
                }
                char a = value[i];
                char b = value[j];
                if (char.ToLower(a) != char.ToLower(b))
                {
                    return false;
                }
                i++;
                j--;
            }
        }

static void Main(string[] args)
{
    string str, rev="";

    Console.Write("Enter string");

    str = Console.ReadLine();

    for (int i = str.Length - 1; i >= 0; i--)
    {
        rev = rev + str[i];
    }

    if (rev == str)
        Console.Write("Entered string is pallindrome");
    else
        Console.Write("Entered string is not pallindrome");

    Console.ReadKey();
}

public Boolean IsPalindrome(string value)
{
   var one = value.ToList<char>();
   var two = one.Reverse<char>().ToList();
   return one.Equals(two);
}

    public static bool IsPalindrome(string str)
    {
        int i = 0;
        int a = 0;

        char[] chr = str.ToCharArray();
        foreach (char cr in chr)
        {
            Array.Reverse(chr);
            if (chr[i] == cr)
            {
                if (a == str.Length)
                {
                    return true;
                }
                a++;
                i++;
            }
            else
            {
                return false;
            }
        }
        return true;
    }

The various provided answers are wrong for numerous reasons, primarily from misunderstanding what a palindrome is. The majority only properly identify a subset of palindromes.

From Merriam-Webster

A word, verse, or sentence (such as "Able was I ere I saw Elba")

And from Wordnik

A word, phrase, verse, or sentence that reads the same backward or forward. For example: A man, a plan, a canal, Panama!

Consider non-trivial palindromes such as "Malayalam" (it's a proper language, so naming rules apply, and it should be capitalized), or palindromic sentences such as "Was it a car or a cat I saw?" or "No 'X' in Nixon".

These are recognized palindromes in any literature.

I'm lifting the thorough solution from a library providing this kind of stuff that I'm the primary author of, so the solution works for both String and ReadOnlySpan<Char> because that's a requirement I've imposed on the library. The solution for purely String will be easy to determine from this, however.

public static Boolean IsPalindrome(this String @string) =>
    !(@string is null) && @string.AsSpan().IsPalindrome();

public static Boolean IsPalindrome(this ReadOnlySpan<Char> span) {
    // First we need to build the string without any punctuation or whitespace or any other
    // unrelated-to-reading characters.
    StringBuilder builder = new StringBuilder(span.Length);
    foreach (Char s in span) {
        if (!(s.IsControl()
            || s.IsPunctuation()
            || s.IsSeparator()
            || s.IsWhiteSpace()) {
            _ = builder.Append(s);
        }
    }
    String prepped = builder.ToString();
    String reversed = prepped.Reverse().Join();
    // Now actually check it's a palindrome
    return String.Equals(prepped, reversed, StringComparison.CurrentCultureIgnoreCase);
}

You're going to want variants of this that accept a CultureInfo parameter as well, when you're testing a specific language rather than your own language, by instead calling .ToUpper(cultureInfo) on prepped.

And here's proof from the projects unit tests that it works.

unit test results


This C# method will check for even and odd length palindrome string (Recursive Approach):

public static bool IsPalindromeResursive(int rightIndex, int leftIndex, char[] inputString)
{
    if (rightIndex == leftIndex || rightIndex < leftIndex)
        return true;
    if (inputString[rightIndex] == inputString[leftIndex])
        return IsPalindromeResursive(--rightIndex, ++leftIndex, inputString);
    else
        return false;            
}

That is non-trivial, there is no built in method to do that for you, you'll have to write your own. You will need to consider what rules you would like to check, like you implicitly stated you accepted reversing of one string. Also, you missed out the middle character, is this only if odd length?

So you will have something like:

if(myString.length % 2 = 0)
{
     //even
     string a = myString.substring(0, myString.length / 2);
     string b = myString.substring(myString.length / 2 + 1, myString.lenght/2);

     if(a == b)
           return true;

     //Rule 1: reverse
     if(a == b.reverse()) //can't remember if this is a method, if not you'll have to write that too
           return true;

etc, also doing whatever you want for odd strings


protected bool CheckIfPalindrome(string text)
{
    if (text != null)
    {
        string strToUpper = Text.ToUpper();
        char[] toReverse = strToUpper.ToCharArray();
        Array.Reverse(toReverse );
        String strReverse = new String(toReverse);
        if (strToUpper == toReverse)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    else
    {
        return false;
    }
}

Use this the sipmlest way.


string test = "Malayalam";
            char[] palindrome = test.ToCharArray();
            char[] reversestring = new char[palindrome.Count()];
            for (int i = palindrome.Count() - 1; i >= 0; i--)
            {
                reversestring[palindrome.Count() - 1 - i] = palindrome[i];

            }

            string materializedString = new string(reversestring);

            if (materializedString.ToLower() == test.ToLower())
            {
                Console.Write("Palindrome!");
            }
            else
            {
                Console.Write("Not a Palindrome!");
            }

            Console.Read();

    public  bool MojTestPalindrome (string word)
    {
        bool yes = false;

        char[]test1 = word.ToArray();
        char[] test2 = test1.Reverse().ToArray();
        for (int i=0; i< test2.Length; i++)
        {

            if (test1[i] != test2[test2.Length - 1 - i])
            {

                yes = false;
                break;

            }
            else {   
                yes = true;


            }
        }
        if (yes == true)
        {
            return true;
        }
        else

            return false;                
    }

public bool Solution(string content)
    {
        int length = content.Length;

        int half = length/2;

        int isOddLength = length%2;

        // Counter for checking the string from the middle 
        int j = (isOddLength==0) ? half:half+1;

        for(int i=half-1;i>=0;i--)
        {                
            if(content[i] != content[j])
            {
               return false;
            }
            j++;

        }
        return true;
    }

Using LINQ and off course far from the best solution

var original = "ankYkna";
var reversed = new string(original.Reverse().ToArray());
var palindrom = original == reversed;

Out of all the solutions, below can also be tried:

public static bool IsPalindrome(string s)
{
    return s == new string(s.Reverse().ToArray());
}

If you just need to detect a palindrome, you can do it with a regex, as explained here. Probably not the most efficient approach, though...


Just for fun:

return myString.SequenceEqual(myString.Reverse());

int length = myString.Length;
for (int i = 0; i < length / 2; i++)
{
    if (myString[i] != myString[length - i - 1])
        return false;
}
return true;

static void Main(string[] args)
        {
            Console.WriteLine("Enter a string to check pallingdrome i.e startreverse is same");
            string str = Convert.ToString( Console.ReadLine());

            char[] arr = str.ToCharArray();
            var strLength = arr.Length-1;
            string newStr = "";
            for (var i= strLength; i < arr.Length; i--)
            {

                newStr = newStr + Convert.ToString(arr[i]);
                if(i==0)
                {
                    break;
                }
            }
            if(str==newStr)
            {
                Console.WriteLine("Entered key is Palindrome");
                Console.ReadLine();
            }
            else
            {
                Console.WriteLine("Entered key is not Palindrome");
                Console.ReadLine();
            }

        }