C# Remove special characters

后端 未结 7 2338
孤街浪徒
孤街浪徒 2021-02-07 08:08

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

7条回答
  •  爱一瞬间的悲伤
    2021-02-07 08:50

    Cast each char to an int, then compare its ascii code to the ascii table, which you can find all over the internet: http://www.asciitable.com/

        {
            char[] input = txtInput.Text.ToCharArray();
            StringBuilder sbResult = new StringBuilder();
    
            foreach (char c in input)
            {
                int asciiCode = (int)c;
                if (
                    //Space
                    asciiCode == 32
                    ||
                    // Period (.)
                    asciiCode == 46
                    ||
                    // Percentage Sign (%)
                    asciiCode == 37
                    ||
                    // Underscore
                    asciiCode == 95
                    ||
                    ( //0-9, 
                        asciiCode >= 48
                        && asciiCode <= 57
                    )
                    ||
                    ( //A-Z
                        asciiCode >= 65
                        && asciiCode <= 90
                    )
                    ||
                    ( //a-z
                        asciiCode >= 97
                        && asciiCode <= 122
                    )
                )
                {
                    sbResult.Append(c);
                }
            }
    
            txtResult.Text = sbResult.ToString();
        }
    

提交回复
热议问题