Check if a string contains one of 10 characters

前端 未结 6 916
情话喂你
情话喂你 2020-12-04 12:01

I\'m using C# and I want to check if a string contains one of ten characters, *, &, # etc etc.

What is the best way?

6条回答
  •  自闭症患者
    2020-12-04 12:17

    The following would be the simplest method, in my view:

    var match = str.IndexOfAny(new char[] { '*', '&', '#' }) != -1
    

    Or in a possibly easier to read form:

    var match = str.IndexOfAny("*&#".ToCharArray()) != -1
    

    Depending on the context and performance required, you may or may not want to cache the char array.

提交回复
热议问题