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?
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.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With