Finding words in a List ?

Hello

I have a List that contain: “ABCDEFGHIJKLMNOPQRSTUVWXYZ”.
I need find words in this List, for example: CAKE, COFFEE, BALL, APPLE, and others.

I tried follow this example: http://msdn.microsoft.com/en-us/library/aa287730(v=vs.71).aspx
but doesn’t work.

I’m trying this.

private List<String> wordsCollected = new List<string>();
wordsCollected.Add("A");
wordsCollected.Add("B");
wordsCollected.Add("C");
wordsCollected.Add("D");
wordsCollected.Add("E");
wordsCollected.Add("F");
wordsCollected.Add("G");
wordsCollected.Add("H");
wordsCollected.Add("I");
wordsCollected.Add("J");
wordsCollected.Add("K");
//others

//word to find
private string wordToFind = "CAKE";


/**
*  this method should find word CAKE 
*  Remember that List<string> have ABCDEFGHIJKL and not word CAKE
*/
public bool isWordFound(){
    bool found = false;
    foreach(string x in wordsCollected){
        found = wordsCollected[x].IndexOf(wordToFind);
        if(found > -1){
           //CAKE IS FOUND           
           found = true;
        }  
    }
    return found;
}
   
}

How can I do this ?

Are you getting an error or is the code not working?

Try changing line 21 to 24 to something like: found = wordsCollected[x].Contains(wordFind); if(found){ break; }

I tried and still doesn't work :(

What error are you getting

I did: Debug.Log(wordsCollected[x].Contains(wordFind)) does returns always false

1 Answer

1

You don’t use the IndexOf function correctly. The function looks for a certain value in a list and returns the index of the found element. If no match is found it returns -1. So you simply want to look for your value wordFind in wordsCollected by calling wordsCollected.IndexOf(wordFind). If a number different than -1 is returned, than you found a match. This results in the following very simple code:

public bool isWordFound(){   
    return wordsCollected.IndexOf(wordFind) != -1;
}

I did /** check if word is contained */ public bool isWordFound(){ int found = 0; bool contain = false; string wordFind = "CAKE"; found = wordsCollected.IndexOf(wordFind); if(found > -1){ contain = true; } return contain; } and still doesn't work

I'm trying use Where with List, but in Unity doesn't work ?