Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if the string contains all inputs on the list

Tags:

c#

I want to be able to check if the string contains all the values held in the list; So it will only give you a 'correct answer' if you have all the 'key words' from the list in your answer. Heres something i tired which half fails;(Doesn't check for all the arrays, will accept just one). Code i tired:

 foreach (String s in KeyWords)
        {
            if (textBox1.Text.Contains(s))
            {
                correct += 1;
                MessageBox.Show("Correct!");
                LoadUp();
            }
            else
            {
                incorrect += 1;
                MessageBox.Show("Incorrect.");
                LoadUp();
            }
        }

Essentially what i want to do is:

Question: What is the definition of Psychology?

Key words in arraylist: study,mental process,behaviour,humans

Answer: Psychology is the study of mental process and behaviour of humans

Now if and ONLY if the answer above contains all key words will my code accept the answer. I hope i have been clear with this.

Edit: Thank you all for your help. All answers have been voted up and i thank everyone for quick answers. I voted up the answer that can be easily adapted to any code. :)

like image 527
Metab Avatar asked Feb 06 '13 11:02

Metab


2 Answers

This should help:

 string text = "Psychology is the study of mental process and behaviour of humans";
 bool containsAllKeyWords = KeyWords.All(text.Contains);
like image 76
algreat Avatar answered Sep 29 '22 01:09

algreat


Using LINQ:

// case insensitive check to eliminate user input case differences
var invariantText = textBox1.Text.ToUpperInvariant();
bool matches = KeyWords.All(kw => invariantText.Contains(kw.ToUpperInvariant()));
like image 32
sll Avatar answered Sep 29 '22 02:09

sll