public bool ContainAnyOf(string word, string[] array)
{
for (int i = 0; i < array.Length; i++)
{
if (word.Contains(array[i]))
{
return true;
}
}
return false;
}
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;
}
}
下面是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;
}
如果stringArray中的所有字符串都具有相同的长度,那么最好使用HashSet而不是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;
}
string strName = "vernie";
string[] strNamesArray = { "roger", "vernie", "joel" };
if (strNamesArray.Any(x => x == strName))
{
// do some action here if true...
}