Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 268059
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 11, 20262026-05-11T23:38:30+00:00 2026-05-11T23:38:30+00:00

I want to remove all special characters from a string. Allowed characters are A-Z

  • 0

I want to remove all special characters from a string. Allowed characters are A-Z (uppercase or lowercase), numbers (0-9), underscore (_), or the dot sign (.).

I have the following, it works but I suspect (I know!) it’s not very efficient:

    public static string RemoveSpecialCharacters(string str)
    {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < str.Length; i++)
        {
            if ((str[i] >= '0' && str[i] <= '9')
                || (str[i] >= 'A' && str[i] <= 'z'
                    || (str[i] == '.' || str[i] == '_')))
                {
                    sb.Append(str[i]);
                }
        }

        return sb.ToString();
    }

What is the most efficient way to do this? What would a regular expression look like, and how does it compare with normal string manipulation?

The strings that will be cleaned will be rather short, usually between 10 and 30 characters in length.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-11T23:38:31+00:00Added an answer on May 11, 2026 at 11:38 pm

    Why do you think that your method is not efficient? It’s actually one of the most efficient ways that you can do it.

    You should of course read the character into a local variable or use an enumerator to reduce the number of array accesses:

    public static string RemoveSpecialCharacters(this string str) {
       StringBuilder sb = new StringBuilder();
       foreach (char c in str) {
          if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '.' || c == '_') {
             sb.Append(c);
          }
       }
       return sb.ToString();
    }
    

    One thing that makes a method like this efficient is that it scales well. The execution time will be relative to the length of the string. There is no nasty surprises if you would use it on a large string.

    Edit:
    I made a quick performance test, running each function a million times with a 24 character string. These are the results:

    Original function: 54.5 ms.
    My suggested change: 47.1 ms.
    Mine with setting StringBuilder capacity: 43.3 ms.
    Regular expression: 294.4 ms.

    Edit 2:
    I added the distinction between A-Z and a-z in the code above. (I reran the performance test, and there is no noticable difference.)

    Edit 3:
    I tested the lookup+char[] solution, and it runs in about 13 ms.

    The price to pay is, of course, the initialization of the huge lookup table and keeping it in memory. Well, it’s not that much data, but it’s much for such a trivial function…

    private static bool[] _lookup;
    
    static Program() {
       _lookup = new bool[65536];
       for (char c = '0'; c <= '9'; c++) _lookup[c] = true;
       for (char c = 'A'; c <= 'Z'; c++) _lookup[c] = true;
       for (char c = 'a'; c <= 'z'; c++) _lookup[c] = true;
       _lookup['.'] = true;
       _lookup['_'] = true;
    }
    
    public static string RemoveSpecialCharacters(string str) {
       char[] buffer = new char[str.Length];
       int index = 0;
       foreach (char c in str) {
          if (_lookup[c]) {
             buffer[index] = c;
             index++;
          }
       }
       return new string(buffer, 0, index);
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I want to remove all special characters from a string. Allowed characters are A-Z
I want to remove all special characters except space from a string using JavaScript.
I want to remove all non-alphanumeric and space characters from a string. So I
I want to remove all strange characters from a string to make it url
I want to remove all special characters (,/{}etc.) from an input field being saved
I want to do a string replace, to remove all of the special and
I want to remove all the unpartnered or unpaired parenthesises from a string. exampleStr
In a table column in string we can have numbers/special chars/white spaces. I want
i have the following problem. I want to escape all special characters in a
I want to remove all files from Git at ~/bin/. I run git rm

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.