Palindrome Check: Normalize Strings in C#

Introduction

I just had a technical interview with a multinational corporation and was asked a C# query about string manipulation. The interviewer asked how to normalize a string—that is, to remove whitespace and special characters without changing the string's capitalization—and then determine whether the resulting string is a palindrome. This question put my knowledge of string normalization and my C# problem-solving abilities to the test.

Question

Write a C# function that takes a given string and normalizes it by removing all special characters and whitespace while keeping the capitalization intact. Check to see if the resultant string is a palindrome after normalization.

Below is a C# implementation

using System;

public class StringManipulation
{
    public static bool IsPalindrome(string input)
    {
        // Normalize the string by removing special characters and spaces
        string temp = "";

        foreach (char c in input)
        {
            // Check if the character is alphanumeric
            if (char.IsLetterOrDigit(c))
            {
                // Convert to lowercase and add to the normalized string
                temp += char.ToLower(c);
            }
        }

        int length = temp.Length;
        for (int i = 0; i < length / 2; i++)
        {
            // Compare characters from the start and the end
            if (temp[i] != temp[length - i - 1])
            {
                return false; // Not a palindrome
            }
        }

        return true; // Is a palindrome
    }

    public static void Main(string[] args)
    {
        string newString = "r(e@ a $e^r";
        
        bool res = IsPalindrome(newString);
        
        Console.WriteLine($"Is the string \"{newString}\" a palindrome? {res}");
    }
}

Explanation

  • Initializing an empty string named Temp is the first step taken by the method IsPalindrome.
  • The input string is iterated over, and char is used to determine if each character is alphanumeric.IsDigitOrLetter (c). Should this be the case, the character is lowered in case and added to Temp.
  • The function then compares characters from the string's beginning and end to see if the normalized string is a palindrome. A for loop that iterates through the string until it reaches the middle and returns false if any characters do not match is used to do this. The function returns true if every character matches.
  • Using the sample input string "r(e@ a $e^r")," we test the function in the Main method and show the outcome.

Conclusion

Through our C# implementation, we were able to show how to properly normalize a string, keeping the original capitalization while eliminating special characters and whitespace. By iterating through the characters in the normalized string, the function looks for palindromic properties.


Similar Articles