1

how to find number of array list same as contains string, i want make contains string "guess1" get "answer1" and "guess2" get "answer2". how to find n number of array same as contains string?

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

List<string> guess = new List<string>();
List<string> answer = new List<string>();

private int n;

void Start()
{
    guess.Add("test1");
    guess.Add("test2");

    answer.Add("answer1");
    answer.Add("answer2");
}

// Update is called once per frame
void Update()
{
    foreach (string x in guess)
    {
        
        if (intext.text.ToLower().Contains(x.ToLower()))
        {
            text.text = answer[n];
            return;
        } 
    }
    text.text = "not found";
}
}
0

1 Answer 1

2

Then you should use Dictionary type.

private Dictionary<string, string> guessAnswerDict = new Dictionary<string, string>();

private void Start()
{
    guessAnswerDict["test1"] = "answer1";
    guessAnswerDict["test2"] = "answer2";
}

You can check whether the test exists in Dictionary with

guessAnswerDict.Contains("test1");

And get the answer value with

var answer = guessAnswerDict["test1"];

It will throw an exception when there are no key in dictionary, so you have to check it with Contains.

Of course you can merge these two with TryGetValue, like

string answer;
guessAnswerDict.TryGetValue("test1", out answer);

// Totally identical!!
guessAnswerDict.TryGetValue("test1", out var answer);

TryGetValue will return false if there are no key in the dictionary.

BTW, although C#'s default access modifier is private, it's always good to explicitly write it's private, which will increase the readability of your code :)

Sign up to request clarification or add additional context in comments.

2 Comments

thankyou for your reply, how i change "test1" to variable so i can check to "test2" ,"test3",... when input text same as guess ?
Just what you said! var test = userInput; var answer guessAnswerDict[userInput];

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.