How to reverse words using a stack

I am a graduate student taking a second level C# course.  This is don't get snippy trying to sniff me out  :)

2 text boxes..and 1 button.

The click event on button1 should read whatever word (or number) is typed in textbox1 and output to  textbox2 whether or not the input in textbox1 is a palindrome.  (ie "level" in textbox1, when button1 is clicked, textbox2 will read "level is a palindrome"...whereas "lever" in textbox1, when button1 is clicked, textbox2 will read "lever is NOT a palindrome".)  This needs to work for words or numbers.  I've done stuff like this before in C++ using various functions, but am unclear how to do this in c# using a stack.

The core dificulty for me lies in the not knowing how to separate the characters within the stack.  Its simple enough to pop off words in reverse order (ie push green, push red.....pop red, pop green), but how do I do that with the actual characters?

Any thoughts would be greatly appreciated.


Who is Participating?
tgannettsConnect With a Mentor Commented:
Another option is to use the Stack class held in System.Collections to create a First-In-Last-Out method:

string reversed = "";
Stack test;
test = new Stack(this.textBox1.Text.ToCharArray());

while(test.Count > 0)
     reversed += test.Pop();


You can use the Arraylist to store the characters held in the text field of the textbox, and then the reverse method to reverse the order of the letters.

So a possible function to check for a palindrome could be:

string reversed = "";
//Pass characters to arraylist
ArrayList al = new ArrayList(this.textBox1.Text.ToCharArray());

//Sort Arraylist

//Pass arraylist to string
foreach(char letter in al)
     reversed += letter;

if(reversed.ToUpper() == this.textBox1.Text.ToUpper())
     this.textBox2.Text = this.textBox1.Text.ToString() + " is a palindrome";
     this.textBox2.Text = this.textBox1.Text.ToString() + " is not a palindrome";

You would need to ignore spaces if you are trying to check if sentences are palindromes, as any string comparision would fail if the spaces don't match.

Hope this points you in the right direction for your homework!

smccloudAuthor Commented:
Thanks Tom!!!

dekroW ekil a mrahc     :)
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.