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

本文关键字:短语 单词匹 是否 何检查 检查 列表 字符串 | 更新日期: 2023-09-27 18:03:49

我有一个字符串列表

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查询我可以编写?

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

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)));
        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(ss=>ss.Split(''((代替"incuded"(愚蠢的打字错误(。在所有情况下都是唯一的((。

我尽我所能把它排成一行:(

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);