1

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

Updated:

I d'nt want to use Reverse function.

santosh singh
  • 27,666
  • 26
  • 83
  • 129
  • 8
    was there a question there, or do you just want us to do your homework for you? – BlackICE Feb 22 '11 at 16:04
  • 2
    The optimal way of performing a palindrome check would not use LINQ's Reverse command as that has to parse every item in the sequence, which means iterating the whole thing more than once when really, you should only need to look at each element of the string no more than once (and if it's an odd-lengthed string, one character need not be looked at at all). What I'm saying is - LINQ isn't the best thing for this algorithm. – Jeff Yates Feb 22 '11 at 16:12

7 Answers7

7
var result = Enumerable
                .SequenceEqual(text.ToCharArray(), text.ToCharArray()
                .Reverse());
Dave New
  • 38,496
  • 59
  • 215
  • 394
pooja_cute
  • 246
  • 1
  • 3
  • 7
  • you should have this handle the case issue. – msarchet Feb 22 '11 at 16:11
  • this algorithm is good, but it works only for a single, all-lowercase word. Many complex palindromes are multiple words, and word breaks aren't counted when determining symmetry. – KeithS Feb 22 '11 at 16:15
  • This approach would likely work fine if it was a linked list of *numbers* (although not 100% relevant to OP) - correct me, if I'm wrong. – dylanh724 Apr 11 '22 at 07:48
3

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.

Community
  • 1
  • 1
msarchet
  • 15,104
  • 2
  • 43
  • 66
3

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;
}
Jim Mischel
  • 131,090
  • 20
  • 188
  • 351
2

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);
as-cii
  • 12,819
  • 4
  • 41
  • 43
1
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);
KeithS
  • 70,210
  • 21
  • 112
  • 164
  • This looks useful, but I'd like to point out that the overzealous use of anonymous `var` types is not going to help folks learning. Since we can see the C# tag and we're talking about LINQ, we should include explicit typings in examples. – dylanh724 Apr 11 '22 at 07:38
0

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

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

}

Vicky
  • 1
  • 3
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Oct 19 '22 at 07:27