Thursday, September 25, 2008

Verify the string whether it is palindrome(c#)

Some times we need to verify a string whether it is palindrome, here is a method with stack theory to cope with it.
Let's go!

using System.Collections;//

namespace Palindrome

{

class CStack

{

private int p_index;

private ArrayList list;
//initiate the arraylist

public CStack()

{

list = new ArrayList();

p_index = -1;

}
//return the arraylist length as count number property

public int count { get { return list.Count; } }


//add items into arraylist

public void push(Object item) {

list.Add(item);

p_index++;

}
//retrieve the top data and remove it from arraylist

public object pop() {

object obj = list[p_index];

list.RemoveAt(p_index);

p_index--;

return obj;

}
//remove all data from arraylist

public void clear() {

list.Clear();

p_index = -1;

}
//display all elements of arraylist

public object peek() {

return list[p_index];

}

}
class Program

{

static void Main(string[] args)

{

CStack alist = new CStack();

string ch; Console.WriteLine("input you word....");

string word = Console.ReadLine();

bool isPalindrome = true;
for (int x = 0; x < pos =" 0;"> 0)

{

ch = alist.pop().ToString();

if (ch != word.Substring(pos, 1))

{

isPalindrome = false;

break;

}

pos++;

}

//show the result

if (isPalindrome)

{

Console.WriteLine(word + " is a palindrome");

}

else

{

Console.WriteLine(word+" is not a palindrome");

}

Console.WriteLine();

}

}

}

No comments: