How to Check if a String is a Palindrome in C#

Have you ever needed to check if a string is a palindrome in your C# code? A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward. For example, "racecar" is a palindrome.

In this blog post, I'll show you how to write a C# extension method to check if a string is a palindrome. An extension method is a special kind of static method that allows you to add new methods to existing types without modifying the original type.

Here's the code snippet for the IsPalindrome extension method:
public static bool IsPalindrome(this string input) {
    string normalized = input.ToLower();
    int length = normalized.Length;

    for (int i = 0; i < length / 2; i++) {
        if (normalized[i] != normalized[length-1-i]) {
            return false;
        }
    }
    return true;
}
Let's break down how this method works. First, we create a normalized copy of the input string by converting it to lowercase. This allows us to ignore case when checking for palindromes.

Next, we get the length of the normalized string. We only need to iterate over the first half of the string because we're comparing characters from the beginning and end of the string.

In the for loop, we compare the character at index i with the character at index length-1-i. If they're not equal, we know the string is not a palindrome and we return false.

If we make it through the entire loop without finding a mismatched pair of characters, we know the string is a palindrome and we return true.

To use the IsPalindrome method, simply call it on a string like this:
string myString = "racecar";
bool isPalindrome = myString.IsPalindrome();
The isPalindrome variable will be true because "racecar" is a palindrome.

In conclusion, writing a C# extension method to check if a string is a palindrome is a useful technique to have in your toolbox. I hope you found this blog post helpful in learning how to implement this functionality in your own code!

Comments

Popular posts from this blog

Understanding Related Data Loading in Entity Framework Core

3 Docker Best Practices I Learned from Carlos Nunez