Check if a String is a Palindrome
Q: Implement a method that determines whether a given string is a palindrome or not.
- .NET
- Mid level question
Explore all the latest .NET interview questions and answers
ExploreMost Recent & up-to date
100% Actual interview focused
Create .NET interview for FREE!
Sure, here's an example C# method that determines whether a given string is a palindrome or not:
using System; class Program {
static void Main(string[] args) {
// Prompt the user to enter a string
Console.WriteLine("Enter a string:");
string input = Console.ReadLine(); // Call the IsPalindrome method to determine whether the string is a palindrome or not
if (IsPalindrome(input)) { Console.WriteLine(
Console.WriteLine("The string is a palindrome."); }
}
else { Console.WriteLine(
Console.WriteLine("The string is not a palindrome."); } } static bool IsPalindrome(string str) {
// Convert the string to lowercase and remove any non-alphanumeric characters
string cleanedStr = new string(str.ToLower().ToCharArray().Where(c => Char.IsLetterOrDigit(c)).ToArray()); // Compare the original string to its reverse
return cleanedStr == new string(cleanedStr.Reverse().ToArray()); } }
The IsPalindrome method takes a string input, and returns true if the string is a palindrome (i.e. reads the same backwards as forwards), and false otherwise. The method first converts the string to lowercase and removes any non-alphanumeric characters. It then compares the cleaned string to its reverse using the Reverse method from the LINQ library, and returns the result of the comparison. The Main method prompts the user to enter a string, and then calls the IsPalindrome method to determine whether the string is a palindrome or not. The program outputs a message indicating whether the string is a palindrome or not.


