Here’s an example of a palindrome check code in C#:
using System;
public class PalindromeChecker
{
public static bool IsPalindrome(string word)
{
// Convert the word to lowercase and remove any non-alphanumeric characters
string cleanedWord = RemoveNonAlphanumeric(word.ToLower());
// Check if the cleaned word is a palindrome
int start = 0;
int end = cleanedWord.Length - 1;
while (start < end)
{
if (cleanedWord[start] != cleanedWord[end])
{
return false; // Characters don't match, not a palindrome
}
start++;
end--;
}
return true; // All characters match, it's a palindrome
}
private static string RemoveNonAlphanumeric(string word)
{
// Remove non-alphanumeric characters using regular expressions
return System.Text.RegularExpressions.Regex.Replace(word, @"[^a-zA-Z0-9]", "");
}
}
public class Program
{
public static void Main(string[] args)
{
string word = "A man, a plan, a canal, Panama!";
if (PalindromeChecker.IsPalindrome(word))
{
Console.WriteLine("The word is a palindrome.");
}
else
{
Console.WriteLine("The word is not a palindrome.");
}
}
}
In this code, the IsPalindrome
method takes a word as input and performs the palindrome check. It removes non-alphanumeric characters from the word and converts it to lowercase for case-insensitive comparison. The method uses two pointers, one starting from the beginning and the other from the end, and compares the characters at each position. If any characters don’t match, it returns false
, indicating that the word is not a palindrome. If all characters match, it returns true
, indicating that the word is a palindrome.
The RemoveNonAlphanumeric
method removes any non-alphanumeric characters from the word using regular expressions.
In the Main
method, an example word is provided, and the IsPalindrome
method is called to check if the word is a palindrome. The result is then displayed in the console.
Feel free to modify the code to suit your needs and test it with different words or phrases.