How to find whether a string contains any of the special characters?

后端 未结 10 1324
春和景丽
春和景丽 2020-12-10 01:43

I want to find whether a string contains any of the special characters like !,@,#,$,%,^,&,*,(,)....etc.

How can I do that without looping thorugh all the charact

10条回答
  •  悲哀的现实
    2020-12-10 02:07

    public static bool HasSpecialCharacters(string str)
    {
      string specialCharacters = @"%!@#$%^&*()?/>.<,:;'\|}]{[_~`+=-" +"\"";
      char[] specialCharactersArray = specialCharacters.ToCharArray();
    
      int index = str.IndexOfAny(specialCharactersArray);
      //index == -1 no special characters
      if (index == -1)
        return false;
      else
        return true;
    }
    

提交回复
热议问题