如何检查字符串列表是否与短语中的所有单词匹配?

时间:2013-03-13 18:56:37

标签: c# string search-engine

我有一个字符串列表

string[] arr = new string[] { "hello world", "how are you", "what is going on" };

我需要检查我给出的字符串是否使用了arr

中某个字符串中的每个字词

所以让我说我有

string s = "hello are going on";

这是匹配,因为s中的所有字词都位于arr

中的一个字符串中
string s = "hello world man"

这个不匹配,因为“man”不在arr

中的任何字符串中

我知道如何写一个“更长”的方法来做这个但是有一个很好的linq查询我可以写吗?

3 个答案:

答案 0 :(得分:3)

string[] arr = new string[] { "hello world", "how are you", "what is going on" };
string s = "hello are going on";
string s2 = "hello world man";
bool bs = s.Split(' ').All(word => arr.Any(sentence => sentence.Contains(word)));
bool bs2 = s2.Split(' ').All(word => arr.Any(sentence => sentence.Contains(word)));

答案 1 :(得分:2)

        string[] arr = new string[] { "hello world", "how are you", "what is going on" };

        HashSet<string> incuded = new HashSet<string>(arr.SelectMany(ss => ss.Split(' ')));

        string s = "hello are going on";
        string s2 = "hello world man";

        bool valid1 = s.Split(' ').All(ss => incuded.Contains(ss));
        bool valid2 = s2.Split(' ').All(ss => incuded.Contains(ss));

享受! (我使用散列集来表现,你可以用arr.SelectMany替换“included”(愚蠢的拼写错误)(ss =&gt; ss.Split(''))。所有情况下都是唯一的(。)

答案 2 :(得分:0)

我尽力为它排队:)

var arr = new [] { "hello world", "how are you", "what is going on" };

var check = new Func<string, string[], bool>((ss, ar) => 
    ss.Split(' ').All(y => ar.SelectMany(x => 
        x.Split(' ')).Contains(y)));

var isValid1 = check("hello are going on", arr);
var isValid2 = check("hello world man", arr);