I will check whether the given string is a palindrome or not with 2 options using while and for loop.
It is a simple strategy to traverse the string in reverse using length property. Both options return True or False as their result.
In order to execute the code I’ve created a simple console application to print out the result.
Please find complete code below:
- Using While loop
This logic also takes care of the capitalization of the letters. Therefore, ‘Radar’ and ‘radar’ will give same result.
User input string: “Hello World!”
using System; namespace PracticeConsole { class Program { static void Main(string[] args) { Console.WriteLine("Please input the string and then hit enter:"); string myString = Console.ReadLine(); int min = 0; int max = myString.Length - 1; bool isPalindrome = false; while (true) { if (min > max) { isPalindrome = true; } char a = myString[min]; char b = myString[max]; if (char.ToLower(a) != char.ToLower(b)) { isPalindrome = false; } min++; max--; } Console.WriteLine(isPalindrome); Console.ReadLine(); } } }
Result: False
2. Using For loop
This logic doesn’t takes capitalization of the letters into account. Therefore, ‘Radar’ and ‘radar’ will give different results.
User input string: “radar”
using System; namespace PracticeConsole { class Program { static void Main(string[] args) { Console.WriteLine("Please input the string and then hit enter:"); string myString = Console.ReadLine(); string reversedString= ""; bool isPalindrome = false; for (int i = myString.Length - 1; i >= 0; i--) { reversedString += myString[i].ToString(); } if (reversedString == myString) { isPalindrome = true; return isPalindrome; } else { isPalindrome = false; return isPalindrome; } Console.WriteLine(isPalindrome); Console.ReadLine(); } } }
Result: True