C#: Removing common invalid characters from a string: improve this algorithm

前端 未结 9 941
孤城傲影
孤城傲影 2020-12-29 07:18

Consider the requirement to strip invalid characters from a string. The characters just need to be removed and replace with blank or string.Empty.



        
9条回答
  •  长情又很酷
    2020-12-29 07:35

    This one is faster than HashSet. Also, if you have to perform this action often, please consider the foundations for this question I asked here.

    private static readonly bool[] BadCharValues;
    
    static StaticConstructor()
    {
        BadCharValues = new bool[char.MaxValue+1];
        char[] badChars = { '!', '@', '#', '$', '%', '_' };
        foreach (char c in badChars)
            BadCharValues[c] = true;
    }
    
    public static string CleanString(string str)
    {
        var result = new StringBuilder(str.Length);
        for (int i = 0; i < str.Length; i++)
        {
            if (!BadCharValues[str[i]])
                result.Append(str[i]);
        }
        return result.ToString();
    }
    

提交回复
热议问题