LINQ:检查字符串是否是回文?

发布于 2024-10-18 14:27:36 字数 77 浏览 1 评论 0原文

我想使用 Linq 检查字符串是否是回文。

更新:

我不想使用反向功能。

I want to check whether a string is palindrome or not using Linq.

Updated:

I d'nt want to use Reverse function.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

稚然 2024-10-25 14:27:36
var result = Enumerable
                .SequenceEqual(text.ToCharArray(), text.ToCharArray()
                .Reverse());
var result = Enumerable
                .SequenceEqual(text.ToCharArray(), text.ToCharArray()
                .Reverse());
拍不死你 2024-10-25 14:27:36

字符串

new string(Enumerable.Range(1, input.Length).Select(i => input[input.Length - i]).ToArray())

使用它来反转取自 这个问题
您可以执行类似

public bool isStringPalindrome(String input){
    var reversed = new string(Enumerable.Range(1, input.Length).Select(i => input[input.Length - i]).ToArray());
    return String.Compare(input, reversed, true) == 0;
}

“注意这不会考虑标点符号和空格问题”的操作。

Using this to reverse the string

new string(Enumerable.Range(1, input.Length).Select(i => input[input.Length - i]).ToArray())

taken from this question
you could do something like

public bool isStringPalindrome(String input){
    var reversed = new string(Enumerable.Range(1, input.Length).Select(i => input[input.Length - i]).ToArray());
    return String.Compare(input, reversed, true) == 0;
}

Note this won't take in to consideration punctuation and spacing issues.

霊感 2024-10-25 14:27:36

我突然想到有一个替代的 LINQ 解决方案不需要反转字符串。

bool IsPalindrome(string input)
{
    return
        Enumerable.Range(0, input.Length/2)
                    .Select(i => input[i] == input[input.Length - i - 1])
                    .All(b => b);
}

与所提出的其他解决方案一样,这假设有一个精确回文匹配。它不会忽略空格、标点符号、大小写等。

值得注意的是,该解决方案使用 LINQ 来实现我在下面的原始答案中展示的相同算法。


原始答案:

我不知道你为什么要使用 LINQ 来实现这一点。在我看来,如果您只是为其创建一个方法,那么在代码中执行此操作将会更加高效,并且可读性会更高。

您可以使用与反转字符串相同的逻辑:

public bool IsPalindrome(s)
{
    int i = 0;
    int j = s.Length-1;
    while (i > j)
    {
        if (s[i] != s[j])
            return false;
        ++i;
        --j;
    }
    return true;
}

It occurs to me that there's an alternate LINQ solution that doesn't require reversing the string.

bool IsPalindrome(string input)
{
    return
        Enumerable.Range(0, input.Length/2)
                    .Select(i => input[i] == input[input.Length - i - 1])
                    .All(b => b);
}

As with the other solutions presented, this assumes an exact palindromic match. It doesn't ignore spaces, punctuation, casing, etc.

It's interesting to note that this solution uses LINQ to implement the same algorithm I showed below in my original answer.


Original answer:

I don't know why you'd want to use LINQ for this. Doing it in code is going to be much more efficient and, in my opinion, quite a bit more readable if you just create a method for it.

You can use the same logic that's used to reverse a string:

public bool IsPalindrome(s)
{
    int i = 0;
    int j = s.Length-1;
    while (i > j)
    {
        if (s[i] != s[j])
            return false;
        ++i;
        --j;
    }
    return true;
}
云巢 2024-10-25 14:27:36

您可以使用 IEnumerable.SequenceEquals 方法来检查字符串是否为回文:

var textA = "ABBA".ToCharArray();
var textB = textA.Reverse();

bool isPalindrome = textA.SequenceEqual(textB);

You could use IEnumerable<T>.SequenceEquals method to check if a string is palindrome:

var textA = "ABBA".ToCharArray();
var textB = textA.Reverse();

bool isPalindrome = textA.SequenceEqual(textB);
分分钟 2024-10-25 14:27:36
var testString = "racecar";
//Remove all spaces with a String.Replace if you don't want them counted
//testString = String.Replace(testString, " ", String.Empty);
//and convert to all-lowercase
//testString = testString.ToLowerInvariant();

var forwardArray = testString.ToCharArray();
var reverseArray = forwardArray.Reverse().ToArray();

var isPalindrome = Enumerable.SequenceEqual(forwardArray, reverseArray);

现在,这需要 2N 步执行。您可以通过简单的更改将其减少一半:

var testString = "racecar";
//Remove all spaces with a String.Replace if you don't want them counted
//testString = String.Replace(testString, " ", String.Empty);
//and convert to all-lowercase
//testString = testString.ToLowerInvariant();

//take only half the string (rounded down) each way
var length = testString.Length;
var forwardArray = testString.Take(length/2); 
var reverseArray = testString.Reverse().Take(length/2);

var isPalindrome = Enumerable.SequenceEqual(forwardArray, reverseArray);
var testString = "racecar";
//Remove all spaces with a String.Replace if you don't want them counted
//testString = String.Replace(testString, " ", String.Empty);
//and convert to all-lowercase
//testString = testString.ToLowerInvariant();

var forwardArray = testString.ToCharArray();
var reverseArray = forwardArray.Reverse().ToArray();

var isPalindrome = Enumerable.SequenceEqual(forwardArray, reverseArray);

Now, this executes in 2N steps. You can get it down to half that with a simple change:

var testString = "racecar";
//Remove all spaces with a String.Replace if you don't want them counted
//testString = String.Replace(testString, " ", String.Empty);
//and convert to all-lowercase
//testString = testString.ToLowerInvariant();

//take only half the string (rounded down) each way
var length = testString.Length;
var forwardArray = testString.Take(length/2); 
var reverseArray = testString.Reverse().Take(length/2);

var isPalindrome = Enumerable.SequenceEqual(forwardArray, reverseArray);
泪冰清 2024-10-25 14:27:36

在 C# 中,我们编写一个简单的回文检查
它包含一个程序来反转字符串并检查输入的字符串是否是回文。

    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  
        {  
            revs += s[i].ToString();  
        }  
        if (revs == s) // Checking whether string is palindrome or not  
        {  
            Console.WriteLine("String is Palindrome \n Entered String Was {0} and reverse string is {1}", s, revs);  
        }  
        else  
        {  
            Console.WriteLine("String is not Palindrome \n Entered String Was {0} and reverse string is {1}", s, revs);  
        }  
        Console.ReadKey();  
    }  

In C# we write A simple palindrome check
It contains a program to reverse a string and to check whether a Entered string is palindrome or not.

    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  
        {  
            revs += s[i].ToString();  
        }  
        if (revs == s) // Checking whether string is palindrome or not  
        {  
            Console.WriteLine("String is Palindrome \n Entered String Was {0} and reverse string is {1}", s, revs);  
        }  
        else  
        {  
            Console.WriteLine("String is not Palindrome \n Entered String Was {0} and reverse string is {1}", s, revs);  
        }  
        Console.ReadKey();  
    }  
少年亿悲伤 2024-10-25 14:27:36

一个程序,它将输入作为字符串并检查它是否是回文或
不是。

import java.util.Scanner;

public class Palindrome {
 public static void main(String args[]) {
    String a, b = "";
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter the string you want to check : ");
    a = sc.nextLine();
    sc.close();
    System.out.println(" ");

    int n = a.length();
    for (int i = n - 1; i >= 0; i--) {
        b = b + a.charAt(i);
    }

    if (a.equalsIgnoreCase(b)) {
        System.out.println("The input string of ''" + a + "'' is 
 palindrome.");
    } else {
        System.out.println("The input string of ''" + a + "'' is not 
  palindrome.");
    }
  }

}

A program which takes input as string and check if it is palindrome or
not.

import java.util.Scanner;

public class Palindrome {
 public static void main(String args[]) {
    String a, b = "";
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter the string you want to check : ");
    a = sc.nextLine();
    sc.close();
    System.out.println(" ");

    int n = a.length();
    for (int i = n - 1; i >= 0; i--) {
        b = b + a.charAt(i);
    }

    if (a.equalsIgnoreCase(b)) {
        System.out.println("The input string of ''" + a + "'' is 
 palindrome.");
    } else {
        System.out.println("The input string of ''" + a + "'' is not 
  palindrome.");
    }
  }

}

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文