Reputation: 27
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";
}
}
Upvotes: 1
Views: 73
Reputation: 2240
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 :)
Upvotes: 2