Check if a string is a palindrome, ignoring case and spaces
using System;
using System.Text.RegularExpressions;
public class PalindromeChecker
{
/// <summary>
/// Checks if a string is a palindrome (ignoring case, spaces, and punctuation)
/// </summary>
/// <param name="input">String to check</param>
/// <returns>True if palindrome, false otherwise</returns>
public static bool IsPalindrome(string input)
{
if (string.IsNullOrEmpty(input))
return true;
// Remove non-alphanumeric characters and convert to lowercase
string cleaned = Regex.Replace(input.ToLower(), @"[^a-z0-9]", "");
int left = 0;
int right = cleaned.Length - 1;
while (left < right)
{
if (cleaned[left] != cleaned[right])
return false;
left++;
right--;
}
return true;
}
public static void Main()
{
string[] testCases = {
"A man a plan a canal Panama",
"race a car",
"Was it a car or a cat I saw?",
"Madam",
"hello"
};
foreach (string test in testCases)
{
bool result = IsPalindrome(test);
Console.WriteLine($"'{test}' -> {(result ? "Palindrome" : "Not a palindrome")}");
}
}
}
Views
Lines
Characters
Likes