i would like your help with my program. I'm trying to check if the user input is a palindrome. This is my code.
Stack cstack = new Stack();
Stack rstack = new Stack();
Console.WriteLine("Enter a palindrome string");
string input = Console.ReadLine();
foreach (char c in input)
{
cstack.Push(c);
}
foreach (var v in cstack)
{
rstack.Push(v);
}
if (cstack.Equals(rstack))
{
Console.Write("String is a palindrome");
}
else
{
Console.Write("String is not a palindrome");
}
Console.ReadLine();
So what i hope my code is doing is getting input from the user. Pushing the user input as characters into the cstack using a foreach loop. Reversing the characters in the cstack (Which should hold the users input) into a new stack called rstack using another foreach loop. Then using an if else statement which will check to see if the c stack which holds the original input is equal to the reverse stack. This comparison will determine if the string is a palindrome.
Cheers everyone for the help. I'm glad i didn't come out as an idiot with no clue as to what he was doing.
Sorry guys but would anyone know how to make it so the palindrome ignores case sensitivity. I assume you convert the string into lowercase with the ToLower, but really i have no idea I've never needed a string to be case insensitive before.
Stack<char> cstack = new Stack<char>();
string input = "PoP";
var inputToUpper = input.ToUpper(); /*assuming case senstivity is not to be considered */
foreach (char c in inputToUpper)
{
cstack.Push(c);
}
bool isPalindrome = true;
var noOfItems = cstack.Count;
for(int i=0; i< noOfItems ; i++)
{
if (inputToUpper[i] != cstack.Pop())
{
isPalindrome = false; break;
}
}
if (isPalindrome)
{
Console.WriteLine("Palindrome");
}
else
{
Console.WriteLine("Non Palindrome");
}
You can refer live demo here