1

Why contain only check the last array from list? When I try type test1 result "not found". How try contains string from array list.

public class FindContainsText : MonoBehaviour
{
    public Text text;
    public InputField intext;

    List<string> guess = new List<string>();
    private string answer;
    void Start()
    {
        guess.Add("test1");
        guess.Add("test2");

        answer="ok";
    }

    void Update()
    {
        foreach (string x in guess)
        {
            if (intext.text.ToLower().Contains(x.ToLower()))
            {
                text.text = answer;
            }
            else
            {
                text.text = "not found";
            }
        }
    }
}

2 Answers 2

3

You need to "break out" of the foreach loop when you find it. Otherwise you will continue looping through the elements so unless the last element is it, it will be "not found".

foreach (string x in guess)
{
    if (intext.text.ToLower().Contains(x.ToLower()))
    {
        text.text = answer;
        break;
    }
    else
    {
        text.text = "not found";
    }
}

Also you could use System.Linq to help you out here: Place this at the top of the file.

using System.Linq;

Then use the Contains extension method that Linq provides:

if (guess.Contains(intext.text, StringComparison.OrdinalIgnoreCase))
{
    text.text = answer;
}
else
{
    text.text = "not found";
}
Sign up to request clarification or add additional context in comments.

Comments

2

The problem is you don't stop the loop once you've found the correct answer.

It's not that the loop only checks the last item of the list, it that it checks all the items of the list, even after it found the correct answer you're looking for.

A better implementation would look like this:

void Update()
{
    foreach (string x in guess)
    {
        if (intext.text.ToLower().Contains(x.ToLower()))
        {
            text.text = answer;
            return;
        }
    }
    text.text = "not found";
}

This way, the text would be not found only if the intext.text doesn't contain any of the items of the list.

Note that using linq,
It can be written in a singe line of code:

text.text = guess.Any(x => 
    intext.text.Equals(x, StringComparison.InvariantCultureIgnoreCase))
    ? answer
    : "not found";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.