23

我有一个字符串作为输入,并且必须将字符串分成两个子字符串。如果左子字符串等于右子字符串,则执行一些逻辑。

我怎样才能做到这一点?

样本:

public bool getStatus(string myString)
{

}

示例:myString = "ankYkna",因此如果我们将其分成两个子字符串,它将是: left-part = "ank"right-part = "ank"(反转后)。

4

33 回答 33

89

只是为了好玩:

return myString.SequenceEqual(myString.Reverse());
于 2012-03-20T18:21:36.233 回答
30
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);
}
于 2012-03-20T16:31:35.420 回答
23
int length = myString.Length;
for (int i = 0; i < length / 2; i++)
{
    if (myString[i] != myString[length - i - 1])
        return false;
}
return true;
于 2012-03-20T16:35:28.023 回答
16

使用 LINQ,当然远非最佳解决方案

var original = "ankYkna";
var reversed = new string(original.Reverse().ToArray());
var palindrom = original == reversed;
于 2012-03-20T16:37:28.350 回答
13

一行代码使用Linq

public static bool IsPalindrome(string str)  
{
    return str.SequenceEqual(str.Reverse());
}
于 2012-12-16T03:01:33.637 回答
7
 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--;
            }
        }
于 2014-07-18T02:58:46.547 回答
3

//这个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;
        }
于 2013-07-20T20:48:41.040 回答
2

这种方式外观简洁,处理速度非常快。

Func<string, bool> IsPalindrome = s => s.Reverse().Equals(s);
于 2014-06-11T15:49:21.137 回答
2

在 C# 中:

public bool EhPalindromo(string text)
{
 var reverseText = string.Join("", text.ToLower().Reverse());
 return reverseText == text;
}
于 2019-04-03T23:35:12.083 回答
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;
        }
于 2016-02-14T17:44:05.147 回答
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();
    }
于 2016-08-26T22:59:18.887 回答
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"); 

        }
于 2017-07-11T13:26:22.927 回答
1

从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));
            }
        }
    }
于 2017-12-22T11:05:40.563 回答
1

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

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;

}
于 2018-07-17T20:13:30.573 回答
0

如果您只需要检测回文,您可以使用正则表达式来完成,如此所述。可能不是最有效的方法,虽然......

于 2012-03-20T16:30:23.720 回答
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;

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

于 2012-03-20T16:33:15.760 回答
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;            
}
于 2013-07-20T21:55:57.140 回答
0
public Boolean IsPalindrome(string value)
{
   var one = value.ToList<char>();
   var two = one.Reverse<char>().ToList();
   return one.Equals(two);
}
于 2014-04-23T05:11:19.587 回答
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();
    }
}
于 2014-09-13T08:07:22.820 回答
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;
}
于 2015-05-22T14:18:13.610 回答
0

由于回文还包括数字、单词、句子以及它们的任何组合,并且应该忽略标点符号和大小写,(参见维基百科文章)我提出了这个解决方案:

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

}
于 2016-03-02T22:21:03.233 回答
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);
    }

因此,从您的主要方法中,对于偶数和奇数长度的字符串,您只需将整个字符串传递给该方法。

于 2016-10-20T06:15:33.480 回答
0

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

public static bool IsPalindrome(string s)
{
    return s == new string(s.Reverse().ToArray());
}
于 2016-10-20T07:31:56.323 回答
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();
}
于 2017-01-18T12:36:06.180 回答
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();
于 2017-09-13T00:10:01.280 回答
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;
    }
于 2017-11-04T09:23:41.070 回答
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;
    }
于 2018-08-07T19:39:14.190 回答
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;                
    }
于 2019-01-30T17:47:22.433 回答
0
    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;
    }
于 2019-09-18T10:28:43.197 回答
0

由于多种原因,提供的各种答案都是错误的,主要是由于误解了回文是什么。大多数只正确识别回文的子集。

来自韦氏词典

一个词、诗句或句子(例如“我在看到厄尔巴岛之前能够做到”)

来自 Wordnik

向后或向前读相同的单词、短语、诗句或句子。例如:一个人,一个计划,一条运河,巴拿马!

考虑不平凡的回文,例如“马拉雅拉姆语”(这是一种适当的语言,因此适用命名规则,并且应该大写),或回文句子,例如“我看到的是汽车还是猫?” 或“尼克松没有'X'”。

这些在任何文献中都是公认的回文。

我正在从一个提供我是主要作者的这类东西的库中提取彻底的解决方案,因此该解决方案适用于两者StringReadOnlySpan<Char>因为这是我对库强加的要求。但是,pure 的解决方案String很容易从中确定。

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

CultureInfo当您通过调用.ToUpper(cultureInfo).prepped

这是来自项目单元测试的证明,它可以工作。

单元测试结果

于 2020-01-01T18:35:32.173 回答
0
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();
            }

        }
于 2020-03-15T16:36:51.703 回答
0

使用传统方法找到回文的最短技术

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";
}
于 2020-04-30T07:47:21.667 回答
-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());
        }
    }
}
于 2018-01-09T13:32:14.940 回答