检查字符串是否包含列表中的所有输入
我希望能够检查字符串是否包含列表中保存的所有值; 因此,如果您在答案中列出了所有“关键词”,那么它只会给您“正确答案”。 inheritance人我累了哪一半失败了;(不检查所有数组,只接受一个)。 代码我累了:
foreach (String s in KeyWords) { if (textBox1.Text.Contains(s)) { correct += 1; MessageBox.Show("Correct!"); LoadUp(); } else { incorrect += 1; MessageBox.Show("Incorrect."); LoadUp(); } }
基本上我想做的是:
问题:心理学的定义是什么?
关于arraylist的关键词: 研究,心理过程,行为,人类
答:心理学是研究 人类的心理过程和行为
现在,只要上述答案包含所有关键词,我的代码才能接受答案。 我希望我对此很清楚。
编辑:谢谢大家的帮助。 所有答案都已经通过投票,我感谢大家快速解答。 我投了答案,可以很容易地适应任何代码。 🙂
使用LINQ:
// case insensitive check to eliminate user input case differences var invariantText = textBox1.Text.ToUpperInvariant(); bool matches = KeyWords.All(kw => invariantText.Contains(kw.ToUpperInvariant()));
这应该有所帮助:
string text = "Psychology is the study of mental process and behaviour of humans"; bool containsAllKeyWords = KeyWords.All(text.Contains);
您可以使用一些LINQ方法,如:
if(Keywords.All(k => textBox1.Text.Contains(k))) { correct += 1; MessageBox.Show("Correct"); } else { incorrect -= 1; MessageBox.Show("Incorrect"); }
当函数为列表中的所有项返回true时, All
方法返回true。