Forum guidelines
AuthorQuestion
palindrome in c# ?
Posted on: 16 Jul 2013
well hi

I want to check weather the given string is palindrome or not .. i am getting ok for single word string like "sunus" but getting compile time errors while doing with big ones ? like  "a but tuba" ??

Any solution manually appraoch plz

TY

AuthorReply
Re: palindrome in c# ?
Posted on: 16 Jul 2013  
If by 'manually' you mean that you don't want to use any string functions, then try this:

using System;
using System.Text;

class Test
{
   static void Main()
   {
       string[] words = 
       {
          "sunus",
          "a but tuba",
          "rotor",
          "raja", 
          "able was I ere I saw elba",
          "vulpes"
       }; // it's assumed words will always be lower case

       
       var sb = new StringBuilder();

       for(int i = 0; i < words.Length; i++)
       {
          // remove everything except letters from word
          foreach(char c in words[i])
          {
             if (c >= 97 && c <= 122) sb.Append(c);
          }
          string temp = sb.ToString();
          sb.Length = 0;          

          // now reverse the word
          for(int j = temp.Length - 1; j >= 0; j--)
          {
             sb.Append(temp[j]);
          } 
 
          if (temp == sb.ToString())
          {
             Console.WriteLine("'{0}' is a palindrome", words[i]);
          }
          else
          {
             Console.WriteLine("'{0}' is not a palindrome", words[i]);
          }
          sb.Length = 0;
       }
       Console.ReadKey();
   }
}

Re: palindrome in c# ?
Posted on: 16 Jul 2013  
try this:

using System;


    class Program
    {

        static void Main(string[] args)
        {
            string str, revstr;

            Console.WriteLine("Enter Any String to Know It is Palindrome or not");
            str = Console.ReadLine();

            char[] tempstr = str.ToCharArray();
            Array.Reverse(tempstr);
            revstr = new string(tempstr);

            bool caseignore = str.Equals(revstr, StringComparison.OrdinalIgnoreCase);


            if (caseignore == true)
            {
                Console.WriteLine("............" + str + " Is a Palindrome..........");
            }
            else
            {
                Console.WriteLine("............" + str + " Is Not a Palindrome........");
            }

            Console.Read();
        }
    }


"If you Dream it You can do it"
Re: palindrome in c# ?
Posted on: 16 Jul 2013  
If by 'manually' ?? well vulpes can this code done in small way using whatever functions in c# ?? 


Sanjeeb Lenka ty for your reply to :) its way to complex to understand for a guy like me 
            StringComparison.OrdinalIgnoreCase ??? please can u tell me what is it work & ty friend





Re: palindrome in c# ?
Posted on: 16 Jul 2013  
you can check this link for detail description.

http://www.dotnetperls.com/stringcomparison

"If you Dream it You can do it"
Re: palindrome in c# ?
Posted on: 16 Jul 2013  
Here is another way:

       private string CheckPalinDrome(string text)
        {
            //Converting into Upper case and remove blank spaces in between
            text = textBox2.Text.ToUpper().Replace(" ", string.Empty);

            string revText = ReverseString(text);

            if (revText == text)
            {
               return("palindrome");
            }
            else
            {
                return ("Not palindrome");
            }
        }

        private string ReverseString(string s)
        {
            char[] arr = s.ToCharArray();
            Array.Reverse(arr);
            return new string(arr);
        }



Hemant Srivastava { http://hemant-srivastava.blogspot.com/ }
Re: palindrome in c# ?
Posted on: 16 Jul 2013  
Re: palindrome in c# ?
Posted on: 16 Jul 2013  
Ty very very much everyone :) got my thing

Well but Sanjeeb Lenka your solution just superb but only thing is . It is applicable to single word strings but it will prove to be wrong while we consider "a but tuba" this one . I tried

Hemant Srivastava well just awesome Ty but when pallamdrom contains non special chars(comma,&,# ,',...) like " a but, tub'a " may fail

TO every possible mistake . MR.Vulpes code mentioned above is best of sorts once check it

TY very much for all ur whole hearted support to forum & people like me 



Re: palindrome in c# ?
Posted on: 16 Jul 2013  
 Hi Sunil, 

just clarifying your doubt: "Hemant Srivastava well just awesome Ty but when pallamdrom contains non special chars(comma,&,# ,',...) like " a but, tub'a " may fail" 

The code which I provided would work with special characters too..

Hemant Srivastava { http://hemant-srivastava.blogspot.com/ }
Re: palindrome in c# ?
Posted on: 16 Jul 2013  
my code is also working with any string and special character i checked .

"If you Dream it You can do it"
Vulpes
  • 1
  • 0
accepted
Re: palindrome in c# ?
Posted on: 16 Jul 2013   Accepted Answer
Hemant and Sanjeeb,

See if your code can deal with this palindrome:

"Doc, note: I dissent. A fast never prevents a fatness. I diet on cod."

My previous version didn't deal with capitalization as I didn't think that was needed but I've adjusted it now so that it does, again without using any string function:

using System;
using System.Text;

class Test
{
   static void Main()
   {
       string[] words = 
       {
          "sunus",
          "a but tuba",
          "Rotor",
          "raja", 
          "Able was I ere I saw Elba",
          "vulpes",
          "Doc, note: I dissent. A fast never prevents a fatness. I diet on cod."
       };
  
       var sb = new StringBuilder();

       for(int i = 0; i < words.Length; i++)
       {
          // remove everything except letters from word
          foreach(char c in words[i])
          {
             if (c >= 97 && c <= 122) 
                sb.Append(c);
             else if (c >= 65 && c <= 90)
                sb.Append((char)(c + 32)); 
          }
          string temp = sb.ToString();
          sb.Length = 0;          

          // now reverse the word
          for(int j = temp.Length - 1; j >= 0; j--)
          {
             sb.Append(temp[j]);
          } 
          if (temp == sb.ToString())
          {
             Console.WriteLine("'{0}' is a palindrome", words[i]);
          }
          else
          {
             Console.WriteLine("'{0}' is not a palindrome", words[i]);
          }
          sb.Length = 0;
       }
       Console.ReadKey();
   }
}

However, here's an improved way of doing it which doesn't reverse the string but iterates it from both ends at once, comparing characters as it goes:

using System;

class Test
{
   static void Main()
   {
       string[] words = 
       {
          "sunus",
          "a but tuba",
          "Rotor",
          "raja", 
          "Able was I ere I saw Elba",
          "vulpes",
          "Doc, note: I dissent. A fast never prevents a fatness. I diet on cod.",
          "Madam, I'm Eve"
       };
  
       for(int i = 0; i < words.Length; i++)
       {
          string w = words[i].ToLower();
          bool isPalindrome = true;

          for(int j = 0, k = w.Length - 1; j <= k; j++, k--)
          {  
             if (Char.IsLetter(w[j])) 
             {  
                if (char.IsLetter(w[k]))
                {
                   if (w[j] != w[k])
                   {
                     isPalindrome = false;
                     break;
                   }
                } 
                else
                {
                   j--;
                }                                    
             }
             else if (char.IsLetter(w[k]))
             {
                k++;
             }
          }
                       
          if (isPalindrome)
          {
             Console.WriteLine("'{0}' is a palindrome", words[i]);
          }
          else
          {
             Console.WriteLine("'{0}' is not a palindrome", words[i]);
          }

       }
       Console.ReadKey();
   }
}





Re: palindrome in c# ?
Posted on: 17 Jul 2013  
My previous version didn't deal with capitalization  ???

I think it can be done with small modification in your  Foreach loop i.e 
foreach(char c in words[i]) 

when i changed ur foreach loop into something like this its working good for everything ..!!

-------------------- foreach(char c in words[i].ToLower())-----------------

I this this can be done right vulpes :)

Re: palindrome in c# ?
Posted on: 17 Jul 2013  
Hemant Srivastava & Sanjeeb Lenka ty again friends for re-replying 

Well this is i have this simple string like " PL-ATITAL P " saying it as not a pallondrome but thing we we all know it is ...

+ acc to the methods provided by respectively the output will be wen we reverse like

PLATITA-LP which is not equal to PL-ATITALP beocz of that ' - ' ... please once can you cross check with the given string and ping back :) ty ty

thank you :) 

Re: palindrome in c# ?
Posted on: 17 Jul 2013  
Sunil,

Yes, you can allow for capitalization in the way you suggested (i.e. using ToLower) but, as I'd not used any functions in my original version, I wanted to do the same in the updated version :)

The Wikipedia article on palindromes is worth reading:

http://en.wikipedia.org/wiki/Palindrome

It has some more good examples such as:

"Eva, can I stab bats in a cave?"

"Rise to vote, sir"

"Dammit, I'm mad!"


 

Re: palindrome in c# ?
Posted on: 17 Jul 2013  
yes its is useful :) i am done 


Well your above manual code is just fantastic :) just felt the taste of programming language its gives :)

Ty Vulpes & everyone for support

SPONSORED BY

Custom Software Development
MCN is your source for developing solutions involving websites, mobile apps, cloud-computing, databases, BI, back-end services and processes and client-server applications.