Respuestas:
El siguiente sería el método más simple, en mi opinión:
var match = str.IndexOfAny(new char[] { '*', '&', '#' }) != -1
O en una forma posiblemente más fácil de leer:
var match = str.IndexOfAny("*&#".ToCharArray()) != -1
Según el contexto y el rendimiento requeridos, es posible que desee o no almacenar en caché la matriz de caracteres.
Como han dicho otros, use IndexOfAny. Sin embargo, lo usaría de esta manera:
private static readonly char[] Punctuation = "*&#...".ToCharArray();
public static bool ContainsPunctuation(string text)
{
return text.IndexOfAny(Punctuation) >= 0;
}
De esa manera, no terminará creando una nueva matriz en cada llamada. La cadena también es más fácil de escanear que una serie de caracteres literales, en mi opinión.
Por supuesto, si solo va a usar esto una vez, para que la creación desperdiciada no sea un problema, puede usar:
private const string Punctuation = "*&#...";
public static bool ContainsPunctuation(string text)
{
return text.IndexOfAny(Punctuation.ToCharArray()) >= 0;
}
o
public static bool ContainsPunctuation(string text)
{
return text.IndexOfAny("*&#...".ToCharArray()) >= 0;
}
Realmente depende de cuál le resulte más legible, si desea utilizar los caracteres de puntuación en otro lugar y con qué frecuencia se llamará al método.
EDITAR: Aquí hay una alternativa al método de Reed Copsey para averiguar si una cadena contiene exactamente uno de los caracteres.
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;
}
ToCharArraysupuesto, puede utilizar el formulario "en línea" si es necesario.
Si solo desea ver si contiene algún carácter, le recomiendo usar string.IndexOfAny, como se sugiere en otra parte.
Si desea verificar que una cadena contiene exactamente uno de los diez caracteres, y solo uno, entonces se vuelve un poco más complicado. Creo que la forma más rápida sería verificar una intersección y luego verificar si hay duplicados.
private static char[] characters = new char [] { '*','&',... };
public static bool ContainsOneCharacter(string text)
{
var intersection = text.Intersect(characters).ToList();
if( intersection.Count != 1)
return false; // Make sure there is only one character in the text
// Get a count of all of the one found character
if (1 == text.Count(t => t == intersection[0]) )
return true;
return false;
}
String.IndexOfAny(Char[])
Aquí está la documentación de Microsoft .
¡Gracias a todos ustedes! (¡Y principalmente Jon!): Esto me permitió escribir esto:
private static readonly char[] Punctuation = "$€£".ToCharArray();
public static bool IsPrice(this string text)
{
return text.IndexOfAny(Punctuation) >= 0;
}
ya que estaba buscando una buena manera de detectar si una determinada cadena era en realidad un precio o una oración, como 'Demasiado bajo para mostrar'.