As others have said, use IndexOfAny. However, I would use it this way:
private static readonly char[] Punctuation = "*&#...".ToCharArray(); public static bool ContainsPunctuation(string text) { return text.IndexOfAny(Punctuation) >= 0; }
This way you will not create a new array for each call. A string is also easier to scan than a series of character literals, IMO.
Of course, if you are going to use this only once, then the lost creation is not a problem, you can use:
private const string Punctuation = "*&#..."; public static bool ContainsPunctuation(string text) { return text.IndexOfAny(Punctuation.ToCharArray()) >= 0; }
or
public static bool ContainsPunctuation(string text) { return text.IndexOfAny("*&#...".ToCharArray()) >= 0; }
Actually, it depends on what you find more readable, whether you want to use punctuation marks elsewhere and how often this method will be called.
EDIT: Here's an alternative to the Reed Copsi method to find out if a string contains only one of the characters.
private static readonly HashSet<char> Punctuation = new HashSet<char>("*&#..."); public static bool ContainsOnePunctuationMark(string text) { bool seenOne = false; foreach (char c in text) {
Jon Skeet Sep 07 '09 at 19:57 2009-09-07 19:57
source share