El TecnoBaúl de Kiquenet

Kiquenet boring stories

Posts Tagged ‘string’

C# String contains any characters

Posted by kiquenet en 23 diciembre 2014

private static readonly char[] Punctuation = "*&#...".ToCharArray();
public static bool ContainsPunctuation(string text)
   return text.IndexOfAny(Punctuation) >= 0;

var match = str.IndexOfAny("*&#".ToCharArray()) != -1

finding out if a string contains exactly 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)
              // TODO: Experiment to see whether HashSet is really faster than
              // Array.Contains. If all the punctuation is ASCII, there are other
              // alternatives...
              if (Punctuation.Contains(c))
                     if (seenOne) { return false; // This is the second punctuation character } 
                     seenOne = true;
       return seenOne;

Sources: http://stackoverflow.com/questions/1390749/check-if-a-string-contains-one-of-10-characters

Posted in .NET | Etiquetado: | Leave a Comment »