检查字符串是否是回文

问题描述 投票:14回答:30

我有一个字符串作为输入,必须打破两个子串中的字符串。如果左子串等于右子串,则执行一些逻辑。

我怎样才能做到这一点?

样品:

public bool getStatus(string myString)
{

}

例如:myString = "ankYkna",所以如果我们把它分成两个子串,那就是:left-part = "ank"right-part = "ank"(逆转之后)。

c# string palindrome
30个回答
22
投票
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);
}

1
投票

字符串扩展方法,使用方便:

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

1
投票
 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"); 

        }

0
投票

如果您只是需要检测回文,您可以使用正则表达式进行检查,如here所述。可能不是最有效的方法,但......


0
投票

这是非常重要的,没有内置的方法可以为你做到这一点,你必须自己编写。您将需要考虑要检查的规则,例如您隐含地声明您接受了一个字符串的反转。而且,你错过了中间字符,这只是奇数长度?

所以你会有类似的东西:

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;

等,也为奇数字符串做任何你想做的事


0
投票

这个C#方法将检查偶数和奇数长度的回文串(递归方法):

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

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

0
投票
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;
    }
}

用这个最简单的方式。


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

0
投票
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;
}

0
投票

这是一个绝对简单的方法,

  1. 将单词作为输入接收到方法中。
  2. 将临时变量分配给原始值。
  3. 循环显示初始单词,并将最后一个字符添加到您正在构建的反转中,直到初始单词没有更多字符。
  4. 现在使用您创建的备用数据来保存原始值以与构建的副本进行比较。

这是一个很好的方式,因为你不必抛出整数和双精度。你可以使用ToString()方法将它们传递给它们的字符串表示形式的方法。

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

所以从你的main方法来看,对于偶数和奇数长度的字符串,你只需将整个字符串传递给方法。


62
投票

纯娱乐:

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

0
投票

在所有解决方案中,也可以尝试以下方法:

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

0
投票

由于回文也包括数字,单词,句子以及这些的任何组合,并且应该忽略标点符号和案例,(See Wikipedia Article)我建议这个解决方案:

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

}

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

0
投票
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();

0
投票
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;
    }

0
投票

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

0
投票

这是一种检查回文的简短而有效的方法。

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;

}

0
投票
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;
    }

0
投票
    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;                
    }

0
投票

在C#中:

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

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

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

12
投票

使用LINQ并且远离最佳解决方案

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

5
投票

使用Linq的一行代码

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

4
投票
 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--;
            }
        }

2
投票

//这个c#方法将检查偶数和奇数长度的回文串

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

1
投票

这种方式在外观和流程方面都非常简洁。

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

1
投票
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;
        }
© www.soinside.com 2019 - 2024. All rights reserved.