Quick and Dirty way to search for characters in a string

Posted by mbcrump on Geeks with Blogs See other posts from Geeks with Blogs or by mbcrump
Published on Fri, 26 Mar 2010 06:39:45 GMT Indexed on 2010/03/26 13:43 UTC
Read the original article Hit count: 382

Filed under:

I saw this today on StackOverflow, all credit goes to Jon Skeet. I have always used RegEx or loops to check for special chars. This is a more human-friendly way of doing it.

 

Code Snippet
  1. using System;
  2.  
  3. class Program
  4. {
  5.     //field
  6.     private static readonly char[] SpecialChars = "!@#$%^&*()".ToCharArray();
  7.  
  8.     static void Main(string[] args)
  9.     {
  10.         //text to search for
  11.         string text = "michael";
  12.         int indexOf = text.IndexOfAny(SpecialChars);
  13.  
  14.             if (indexOf == -1)
  15.             {
  16.                 Console.WriteLine("no special char");
  17.             }
  18.  
  19.             Console.ReadLine();
  20.     }
  21. }

© Geeks with Blogs or respective owner