C# program to check if String is Palindrome
Here's a C# program that checks if a given string is a palindrome:
using System;
class Program
{
static void Main()
{
string inputString = "radar";
bool isPalindrome = IsPalindrome(inputString);
if (isPalindrome)
{
Console.WriteLine("{0} is a palindrome.", inputString);
}
else
{
Console.WriteLine("{0} is not a palindrome.", inputString);
}
}
static bool IsPalindrome(string inputString)
{
// Remove spaces and convert to lowercase
inputString = inputString.Replace(" ", "").ToLower();
int start = 0;
int end = inputString.Length - 1;
while (start < end)
{
// If characters at start and end positions don't match, it's not a palindrome
if (inputString[start] != inputString[end])
{
return false;
}
start++;
end--;
}
return true;
}
}
In this program, we have the 'IsPalindrome' method that takes a string as input and returns a boolean indicating whether it is a palindrome.
First, we remove any spaces from the string using the 'Replace' method, and then convert it to lowercase using the 'ToLower' method. This ensures that we can compare characters case-insensitively.
Next, we use two pointers, 'start' and 'end', starting from the beginning and end of the string, respectively. We compare the characters at these positions. If they don't match, the string is not a palindrome and we return 'false'. We continue moving the pointers towards the center of the string until they meet.
If the loop completes without finding any mismatched characters, it means the string is a palindrome, and we return 'true'.
In the example above, the output would be:
radar is a palindrome.
The string "radar" reads the same forwards and backwards, making it a palindrome.