una tiene subcadena saber quitar palabra otra letras letra contiene como caracteres caracter cadena buscar c# string

c# - subcadena - Verificar si una cadena contiene uno de 10 caracteres



saber si un string contiene letras c# (6)

Estoy usando C # y quiero verificar si una cadena contiene uno de los diez caracteres, *, &, # etc, etc.

¿Cuál es la mejor manera?


¡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; }

porque estaba buscando una buena manera de detectar si cierta cadena era realmente un precio o una oración, como "Demasiado bajo para mostrar".


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 forma no terminará creando una nueva matriz en cada llamada. La cadena también es más fácil de escanear que una serie de literales de caracteres, IMO.

Por supuesto, si solo va a usar esto una vez, entonces la creación desperdiciada no es 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 qué le resulte más legible, si desea utilizar los caracteres de puntuación en cualquier 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; }


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

Dependiendo del contexto y el rendimiento requerido, puede o no querer almacenar en caché la matriz de caracteres.


Si solo quieres ver si contiene algún caracter, te recomiendo usar string.IndexOfAny, como se sugiere en otro lugar.

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 manera más rápida sería verificar contra una Intersección, 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 (...)


var specialChars = new[] {''//', ''/'', '':'', ''*'', ''<'', ''>'', ''|'', ''#'', ''{'', ''}'', ''%'', ''~'', ''&''}; foreach (var specialChar in specialChars.Where(str.Contains)) { Console.Write(string.Format("string must not contain {0}", specialChar)); }