How to remove special characters from a string in C#

Understanding the Challenge

Before diving into the code, let’s grasp the concept of special characters. Special characters are those that fall outside the realm of alphanumeric characters. 

They include symbols like '@', '#', '$', '%', and more. The goal is to create a C# program that efficiently removes these special characters from a given string and allowed characters are A-Z (uppercase or lowercase) and numbers (0-9).

Method 1: Using Regular Expressions

C# provides a powerful mechanism for string manipulation known as Regular Expressions. This method allows us to define a pattern of characters to match and then remove them from the string.

Here is the code to learn How to remove special characters from a string in C# using Regular Expressions.

using System;
using System.Text.RegularExpressions;

class Program
{
    static void Main()
    {
        string inputString = "Hello@World#$123";
        
        // Define the pattern for special characters
        string pattern = "[^a-zA-Z0-9]";
        
        // Use Regex to replace special characters with an empty string
        string result = Regex.Replace(inputString, pattern, "");
        
        // Display the result
        Console.WriteLine("Original String: " + inputString);
        Console.WriteLine("String without Special Characters: " + result);
    }
}

Output:

Original String: Hello@World#$123
String without Special Characters: HelloWorld123

Code Explanation:

  • The pattern variable defines a regular expression that matches any character that is not an alphanumeric character.
  • Regex.Replace method is then used to replace all occurrences of the matched pattern with an empty string.

Method 2: Iterating Through Characters

For those who prefer a more straightforward approach, iterating through each character of the string is a viable option. This method involves checking if each character is alphanumeric and building a new string without the special characters.

using System;

class Program
{
    static void Main()
    {
        string inputString = "Hello@World#$123";
        
        // Create a StringBuilder to efficiently build the result
        System.Text.StringBuilder resultBuilder = new System.Text.StringBuilder();
        
        // Iterate through each character in the input string
        foreach (char c in inputString)
        {
            // Check if the character is alphanumeric
            if (Char.IsLetterOrDigit(c))
            {
                // Append alphanumeric characters to the result
                resultBuilder.Append(c);
            }
        }
        
        // Convert the StringBuilder to a string
        string result = resultBuilder.ToString();
        
        // Display the result
        Console.WriteLine("Original String: " + inputString);
        Console.WriteLine("String without Special Characters: " + result);
    }
}

Output:

Original String: Hello@World#$123
String without Special Characters: HelloWorld123

Code Explanation:

  • Here we are using StringBuilder to efficiently build the resulting string without repeatedly creating new strings in memory.
  • The foreach loop iterates through each character in the input string, and Char.IsLetterOrDigit method checks if the character is alphanumeric.

Method3: Using Extension Method

This solution is not only readable but also concise and efficient. It provides a clear and understandable way to filter out special characters from a given string in C#.

using System;
using System.Text;

static class StringExtension
{
    static void Main()
    {
        string inputString = "Hello@World#$123";

        
        string result = inputString.RemoveSpecialCharacters();

        // Display the result
        Console.WriteLine("Original String: " + inputString);
        Console.WriteLine("String without Special Characters: " + result);
    }
    
    // Extension method to remove special characters from a string
    public static string RemoveSpecialCharacters(this string str)
    {
        // Create a StringBuilder to efficiently build the result
        StringBuilder sb = new StringBuilder();

        // Iterate through each character in the input string
        foreach (char c in str)
        {
            // Check if the character is a digit, uppercase letter, lowercase letter, '.', or '_'
            if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '.' || c == '_')
            {
                // Append acceptable characters to the result
                sb.Append(c);
            }
        }

        // Convert the StringBuilder to a string
        return sb.ToString();
    }
}

Conclusion

In this post, we’ve explored three methods for removing special characters from a string in C#: using regular expressions and iterating through characters. All these methods have their merits, and the choice between them depends on your preference and the specific requirements of your project.

Programs you might also like:

Shekh Ali
5 1 vote
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments