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

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.