Check if a string is a palindrome

扶醉桌前 提交于 2019-11-26 22:46:27

问题


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).


回答1:


public static bool getStatus(string myString)
{
    string first = myString.Substring(0, myString.Length / 2);
    char[] arr   = myString.ToCharArray();

    Array.Reverse(arr);

    string temp   = new string(arr);
    string second = temp.Substring(0, temp.Length / 2);

    return first.Equals(second);
}



回答2:


Just for fun:

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



回答3:


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



回答4:


Using LINQ and off course far from the best solution

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



回答5:


A single line of code using Linq

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



回答6:


 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--;
            }
        }



回答7:


//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;
        }



回答8:


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

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



回答9:


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;
        }



回答10:


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();
    }



回答11:


 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"); 

        }



回答12:


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));
            }
        }
    }



回答13:


In C# :

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



回答14:


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...




回答15:


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




回答16:


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;            
}



回答17:


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



回答18:


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.




回答19:


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();
    }
}



回答20:


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;
}



回答21:


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.




回答22:


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

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



回答23:


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());
    }

}



回答24:


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();
}



回答25:


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();



回答26:


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;
    }



回答27:


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;

}



回答28:


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;
    }



回答29:


    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;                
    }



回答30:


    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;
    }


来源:https://stackoverflow.com/questions/9790749/check-if-a-string-is-a-palindrome

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!