Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 characters in the string?

like image 223
Manish Avatar asked Mar 26 '10 11:03

Manish


People also ask

How do you check if a string contains any special character in Python?

Method: To check if a special character is present in a given string or not, firstly group all special characters as one set. Then using for loop and if statements check for special characters. If any special character is found then increment the value of c.

How do you check if a string contains any special character in C#?

new Regex(“[^A-Za-z0-9]”) the pattern is used to check whether the string contains special characters or not. IsMatch() function checks the string and returns True if the string contains a special character. int. TryParse(str, out int n) the method returns True if the string contains the number(s).


1 Answers

Use String.IndexOfAny:

private static readonly char[] SpecialChars = "!@#$%^&*()".ToCharArray();  ...  int indexOf = text.IndexOfAny(SpecialChars); if (indexOf == -1) {     // No special chars } 

Of course that will loop internally - but at least you don't have to do it in your code.

like image 95
Jon Skeet Avatar answered Oct 13 '22 00:10

Jon Skeet