Voglio usare C # per verificare se un valore stringa contiene una parola in un array di stringhe. Per esempio,
string stringToCheck = "text1text2text3";
string[] stringArray = { "text1", "someothertext", etc... };
if(stringToCheck.contains stringArray) //one of the items?
{
}
Come posso verificare se il valore stringa per 'stringToCheck' contiene una parola nell'array?
ecco come puoi farlo:
string stringToCheck = "text1";
string[] stringArray = { "text1", "testtest", "test1test2", "test2text1" };
foreach (string x in stringArray)
{
if (stringToCheck.Contains(x))
{
// Process...
}
}
AGGIORNAMENTO: Potrebbe essere che stai cercando una soluzione migliore .. fai riferimento alla risposta di @Anton Gogolev sotto che usa LINQ.
Ecco come:
if(stringArray.Any(stringToCheck.Contains))
/* or a bit longer: (stringArray.Any(s => stringToCheck.Contains(s))) */
Questo controlla se stringToCheck
contiene una qualsiasi sottostringa da stringArray
. Se vuoi assicurarti che contenga tutte le sottostringhe, cambia Any
in All
:
if(stringArray.All(stringToCheck.Contains))
Non è necessario utilizzare LINQ
if (Array.IndexOf(array, Value) >= 0)
{
//Your stuff goes here
}
Basta usare il metodo linq:
stringArray.Contains(stringToCheck)
(Non è possibile aggiungere un commento alle risposte esistenti poiché la mia reputazione è <50)
Modo più semplice e di prova.
bool bol=Array.Exists(stringarray,E => E == stringtocheck);
Qualcosa di simile forse:
string stringToCheck = "text1text2text3";
string[] stringArray = new string[] { "text1" };
if (Array.Exists<string>(stringArray, (Predicate<string>)delegate(string s) {
return stringToCheck.IndexOf(s, StringComparison.OrdinalIgnoreCase) > -1; })) {
Console.WriteLine("Found!");
}
L'uso di Linq e del gruppo metodo sarebbe il modo più rapido e compatto di farlo.
var arrayA = new[] {"element1", "element2"};
var arrayB = new[] {"element2", "element3"};
if (arrayB.Any(arrayA.Contains)) return true;
string strName = "vernie";
string[] strNamesArray = { "roger", "vernie", "joel" };
if (strNamesArray.Any(x => x == strName))
{
// do some action here if true...
}
Provare:
String[] val = { "helloword1", "orange", "grape", "pear" };
String sep = "";
string stringToCheck = "Word1";
bool match = String.Join(sep,val).Contains(stringToCheck);
bool anothermatch = val.Any(s => s.Contains(stringToCheck));
Puoi anche fare la stessa cosa che Anton Gogolev suggerisce di verificare se qualsiasi elemento in stringArray1
corrisponde a qualsiasi elemento in stringArray2
:
if(stringArray1.Any(stringArray2.Contains))
Allo stesso modo tutti gli elementi in stringArray1 corrispondono a tutti gli elementi in stringArray2:
if(stringArray1.All(stringArray2.Contains))
È possibile definire i propri metodi string.ContainsAny()
e string.ContainsAll()
. Come bonus, ho persino gettato un metodo string.Contains()
che consente confronti tra maiuscole e minuscole, ecc.
public static class Extensions
{
public static bool Contains(this string source, string value, StringComparison comp)
{
return source.IndexOf(value, comp) > -1;
}
public static bool ContainsAny(this string source, IEnumerable<string> values, StringComparison comp = StringComparison.CurrentCulture)
{
return values.Any(value => source.Contains(value, comp));
}
public static bool ContainsAll(this string source, IEnumerable<string> values, StringComparison comp = StringComparison.CurrentCulture)
{
return values.All(value => source.Contains(value, comp));
}
}
Puoi testarli con il seguente codice:
public static void TestExtensions()
{
string[] searchTerms = { "FOO", "BAR" };
string[] documents = {
"Hello foo bar",
"Hello foo",
"Hello"
};
foreach (var document in documents)
{
Console.WriteLine("Testing: {0}", document);
Console.WriteLine("ContainsAny: {0}", document.ContainsAny(searchTerms, StringComparison.OrdinalIgnoreCase));
Console.WriteLine("ContainsAll: {0}", document.ContainsAll(searchTerms, StringComparison.OrdinalIgnoreCase));
Console.WriteLine();
}
}
Userò Linq ma può ancora essere fatto attraverso:
new[] {"text1", "text2", "etc"}.Contains(ItemToFind);
Io uso il seguente in un'applicazione console per verificare gli argomenti
var sendmail = args.Any( o => o.ToLower() == "/sendmail=true");
Per completare le risposte sopra, per IgnoreCase controllare l'uso:
stringArray.Any(s => stringToCheck.IndexOf(s, StringComparison.CurrentCultureIgnoreCase) > -1)
public bool ContainAnyOf(string Word, string[] array)
{
for (int i = 0; i < array.Length; i++)
{
if (Word.Contains(array[i]))
{
return true;
}
}
return false;
}
Ho usato un metodo simile a IndexOf di Maitrey684 e al ciclo foreach di Theomax per creare questo. (Nota: le prime 3 righe "stringa" sono solo un esempio di come è possibile creare un array e inserirlo nel formato corretto).
Se si desidera confrontare 2 array, saranno delimitati da punto e virgola, ma l'ultimo valore non ne avrà uno dopo. Se si aggiunge un punto e virgola alla forma di stringa dell'array (ad esempio a; b; c diventa a; b; c;), è possibile eseguire l'abbinamento utilizzando "x;" indipendentemente dalla posizione in cui si trova:
bool found = false;
string someString = "a-b-c";
string[] arrString = someString.Split('-');
string myStringArray = arrString.ToString() + ";";
foreach (string s in otherArray)
{
if (myStringArray.IndexOf(s + ";") != -1) {
found = true;
break;
}
}
if (found == true) {
// ....
}
Per il mio caso, le risposte di cui sopra non hanno funzionato. Stavo controllando una stringa in un array e assegnandola a un valore booleano. Ho modificato la risposta di @Anton Gogolev e rimosso il metodo Any()
e ho inserito stringToCheck
nel metodo Contains()
.
bool = stringArray.Contains(stringToCheck);
prova questo, ecco l'esempio: per verificare se il campo contiene una delle parole nella matrice. Per verificare se il campo (someField) contiene una delle parole nella matrice.
String[] val = { "helloword1", "orange", "grape", "pear" };
Expression<Func<Item, bool>> someFieldFilter = i => true;
someFieldFilter = i => val.Any(s => i.someField.Contains(s));
Prova questo
string stringToCheck = "text1text2text3";
string[] stringArray = new string[] { "text1" };
var t = lines.ToList().Find(c => c.Contains(stringToCheck));
Ti restituirà la linea con la prima incidenza del testo che stai cercando.
string [] lines = {"text1", "text2", "etc"};
bool bFound = lines.Any(x => x == "Your string to be searched");
bFound si imposta su true se la stringa cercata corrisponde a qualsiasi elemento delle 'linee' dell'array.
Se stringArray
contiene un numero elevato di stringhe di varia lunghezza, prendere in considerazione l'uso di Trie per memorizzare e cercare nell'array di stringhe.
public static class Extensions
{
public static bool ContainsAny(this string stringToCheck, IEnumerable<string> stringArray)
{
Trie trie = new Trie(stringArray);
for (int i = 0; i < stringToCheck.Length; ++i)
{
if (trie.MatchesPrefix(stringToCheck.Substring(i)))
{
return true;
}
}
return false;
}
}
Ecco l'implementazione della classe Trie
public class Trie
{
public Trie(IEnumerable<string> words)
{
Root = new Node { Letter = '\0' };
foreach (string Word in words)
{
this.Insert(Word);
}
}
public bool MatchesPrefix(string sentence)
{
if (sentence == null)
{
return false;
}
Node current = Root;
foreach (char letter in sentence)
{
if (current.Links.ContainsKey(letter))
{
current = current.Links[letter];
if (current.IsWord)
{
return true;
}
}
else
{
return false;
}
}
return false;
}
private void Insert(string Word)
{
if (Word == null)
{
throw new ArgumentNullException();
}
Node current = Root;
foreach (char letter in Word)
{
if (current.Links.ContainsKey(letter))
{
current = current.Links[letter];
}
else
{
Node newNode = new Node { Letter = letter };
current.Links.Add(letter, newNode);
current = newNode;
}
}
current.IsWord = true;
}
private class Node
{
public char Letter;
public SortedList<char, Node> Links = new SortedList<char, Node>();
public bool IsWord;
}
private Node Root;
}
Se tutte le stringhe in stringArray
hanno la stessa lunghezza, starai meglio usando solo HashSet
invece di Trie
public static bool ContainsAny(this string stringToCheck, IEnumerable<string> stringArray)
{
int stringLength = stringArray.First().Length;
HashSet<string> stringSet = new HashSet<string>(stringArray);
for (int i = 0; i < stringToCheck.Length - stringLength; ++i)
{
if (stringSet.Contains(stringToCheck.Substring(i, stringLength)))
{
return true;
}
}
return false;
}
Soluzione semplice, non richiesta linq any
String.Join (",", array) .Contains (Value ",");
int result = Array.BinarySearch(list.ToArray(), typedString, StringComparer.OrdinalIgnoreCase);
Prova questo, non c'è bisogno di un loop ..
string stringToCheck = "text1";
List<string> stringList = new List<string>() { "text1", "someothertext", "etc.." };
if (stringList.Exists(o => stringToCheck.Contains(o)))
{
}