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

前端 未结 9 879
孤城傲影
孤城傲影 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:37

    Why would you have REALLY LIKED to do that? The code is absolutely no simpler, you're just forcing a query extension method into your code.

    As an aside, the Contains check seems redundant, both conceptually and from a performance perspective. Contains has to run through the whole string anyway, you may as well just call Replace(bad.ToString(), string.Empty) for every character and forget about whether or not it's actually present.

    Of course, a regular expression is always an option, and may be more performant (if not less clear) in a situation like this.

    0 讨论(0)
  • 2020-12-29 07:41
    char[] BAD_CHARS = new char[] { '!', '@', '#', '$', '%', '_' }; //simple example
    someString = string.Concat(someString.Split(BAD_CHARS,StringSplitOptions.RemoveEmptyEntries));
    

    should do the trick (sorry for any smaller syntax errors I'm on my phone)

    0 讨论(0)
  • 2020-12-29 07:45

    Extra tip: If you don't want to remember the array of char that are invalid for Files, you could use Path.GetInvalidFileNameChars(). If you wanted it for Paths, it's Path.GetInvalidPathChars

    private static string RemoveInvalidChars(string str)
                {
                    return string.Concat(str.Split(Path.GetInvalidFileNameChars(), StringSplitOptions.RemoveEmptyEntries));
                }
    
    0 讨论(0)
提交回复
热议问题