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

前端 未结 9 918
孤城傲影
孤城傲影 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.

提交回复
热议问题