0

I have an if in a foreach and it returns true only if the word I'm searching is the last one and I don't know what to do

public Text InputNrDeImt;
public Text status;
public string rbd;
public string[] bd;
public string path;
public string NrDeImt;

public void OnCheck(){
   
    path = Application.persistentDataPath +"/BazaDeDate.txt";
    StreamReader reader=new StreamReader(path);
    rbd= reader.ReadToEnd();
    
    reader.Close();
    bd=rbd.Split("\n"[0]);
    NrDeImt = InputNrDeImt.text.ToString();


    foreach(string word in bd){
        if(NrDeImt==word){
            status.text= "found";
        }
        else{
            status.text= "Nu este in baza";
        }
    }
    
    
}

the file looks like that

aaa
aab
aba #the word i was looking for 
abb
baa
bab
bba
bbb

and my code only finds the word if it's "bbb"

DarkBee
  • 16,592
  • 6
  • 46
  • 58
  • 1
    Does this answer your question? [C# loop - break vs. continue](https://stackoverflow.com/questions/6414/c-sharp-loop-break-vs-continue) – shingo Jun 08 '23 at 10:05

1 Answers1

3

Your foreach loop will check every word, meaning that it won't stop after it has found the correct word, in short:

aaa // status.text= "Nu este in baza";
aab // status.text= "Nu este in baza";
aba // status.text= "found";
abb // status.text= "Nu este in baza";
baa // status.text= "Nu este in baza";
bab // status.text= "Nu este in baza";
bba // status.text= "Nu este in baza";
bbb // status.text= "Nu este in baza";

So unless you were looking for the last word, as soon as it loops through the last word, the status is updated to the "not found" text again.

You can fix it by breaking the loop as soon as you found your result. And for performance, only set the text once:

status.text = "Nu este in baza"; // default text is not found
foreach(string word in bd){
    if(NrDeImt==word){
        status.text= "found"; // Now set the found text
        break; // stop the loop, we found the text
    }
}
SynerCoder
  • 12,493
  • 4
  • 47
  • 78