Help trying to find a string in a text file

I am likely missing something silly.

I need to check if a string is contained within a text file, as the whole word.

I have set the text file to a list and tested the list (debug the list) and the correct word comes up. I have wrote my own text file. When I check the string (user input, which calls the method from an other script, sending through a string) against the list it does not work. if I code in a word which is in the list it also does not work. If I hard code to add a word to the list it will then work. I am lost as every bit works just not when put together. I have tried uppercase/lowercase. I have also tried both list and arrays.

Thank you in advance for any help

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
public class WordsList : MonoBehaviour
{
    // each word
    private List<string> _wordList = new List<string>();
    // the text file to import from
    [SerializeField]
    private TextAsset _wordListTextFile;
    // one long string for every word
    private string _wordListFileWholeThing;

    private string[] _testWordArray;
    // bool to test
    [SerializeField]
    private bool _correct;
    void Start()
    {
        // create one long string
        _wordListFileWholeThing = _wordListTextFile.ToString();
        // split the string into actual words by line break and add to list
        _wordList.AddRange(_wordListFileWholeThing.Split("\n"[0]));

        //TEST WORD
       // _wordList.Add("BALE"); // manually adding a test word to the list

        _testWordArray = new string[_wordList.Capacity];
        for (int i = 0; i < _wordList.Capacity; i++)
        {
            string test = _wordList.ToString();

            _testWordArray = test;
        }

      

        Debug.Log(_wordList[0]);
        Debug.Log(_wordList[4]);
        Debug.Log(_wordList[12]);
        Debug.Log(_wordList[100]);
        Debug.Log(_wordList.Count);
       
    }
    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.L))
        {
            // test word checker
            _correct = CheckWord(_wordList[12]); // this works
 
        }
        if (Input.GetKeyDown(KeyCode.K)) // this does not work unless I manually add it to the list
        {
          
            // test word checker
            _correct = CheckWordArray("BALE");
        }
    }
    public bool CheckWordArray(string word)
    {
        // bool to check if word is found
        bool wordFound = false;
       
       
        Debug.Log("Word to look up +" + word + "+");
      

        // loop through the list of words
        for(int i = 0; i< _testWordArray.Length; i++)
        {
            // check to see if words equal
            if(Equals(_testWordArray, word))
            {
                Debug.Log("word found in array");
            }
        }
        {
          
        }
        // after loop if word is found return true
        if (wordFound == true)
        {
            return true;
        }
        // if word not found return false
        else
        {
            return false;
        }
       
    }
    public bool CheckWord(string word)
    {
        // bool to check if word is found
        bool wordFound = false;
       
        // loop through the list of words
        foreach (string str in _wordList)
        {
            // only check if word not already found
            if (wordFound == false)
            {
                str.Trim();
                str.TrimEnd();
                str.TrimStart();
                //if word is found set bool true
              
                if (Equals(str, word))
                {
                    Debug.Log("Word found in fucking list!");
                    // set the bool true if word is found
                    wordFound = true;
                    // break out of loop as no need to run anyfurther
                    // break;
                }
            }
        }
        // after loop if word is found return true
        if (wordFound == true)
        {
            return true;
        }
        // if word not found return false
        else
        {
            return false;
        }
    }
}

Please use code tags: https://discussions.unity.com/t/481379

How to report problems productively in the Unity3D forums:

http://plbm.com/?p=220

1 Like

Thank you, it’s all learning

Line 75:

if(Equals(_testWordArray, word))

Why are you comparing the string to the entire array. I think you probably meant this:

if(Equals(_testWordArray[i], word))

And while you’re at it don’t use the generic object.Equals method so you get compiler errors if you mess up:

if(_testWordArray[i] == word)
2 Likes

It is!

I recommend a couple of things:

  1. make a TINY list of words (like 3 different words)
  2. at line 100 above, print out the two things you’re comparing

That should cause you to immediately move to the next step of the problem. Whenever you have code that behaves weirdly as a result of data, PRINT OUT THAT DATA! It actually works 100% of the time.

2 Likes

Thank you for your replies, I have changed the code numerous times, and I had tried the code above. I have changed it as above and will link it (correctly this time) below. I have debugged the words on a small list and yet the bool is still returning false. With the following in the console.

just a quick note its line 82 that I am trying to get return( Debug.Log(“word found in array”):wink:

Test Word BALE
= BALE
UnityEngine.Debug:Log(Object)
WordsList:CheckWordArray(String) (at Assets/Scripts/WordsList.cs:94)
WordsList:Update() (at Assets/Scripts/WordsList.cs:75)

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
public class WordsList : MonoBehaviour
{
    // each word
    private List<string> _wordList = new List<string>();
    // the text file to import from
    [SerializeField]
    private TextAsset _wordListTextFile;
    // one long string for every word
    private string _wordListFileWholeThing;

    private string[] _testWordArray;
    // bool to test
    [SerializeField]
    private bool _correct;
    void Start()
    {
        // create one long string
        _wordListFileWholeThing = _wordListTextFile.ToString();
        // split the string into actual words by line break and add to list
        _wordList.AddRange(_wordListFileWholeThing.Split("\n"[0]));

        //TEST WORD
       // _wordList.Add("garbed");

        _testWordArray = new string[_wordList.Capacity];
        for (int i = 0; i < _wordList.Capacity; i++)
        {
            string test = _wordList[i].ToString();

            _testWordArray[i] = test;
        }

      

        Debug.Log(_wordList[0]);
        Debug.Log(_wordList[1]);
        Debug.Log(_wordList[2]);
        Debug.Log(_wordList[3]);
        Debug.Log(_wordList.Count);
       
    }
    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.L))
        {
            // test word checker
            _correct = CheckWord(_wordList[12]);
 
        }
        if (Input.GetKeyDown(KeyCode.K))
        {
            string testWord = "garbed";
            testWord.Trim();
            testWord.TrimEnd();
            testWord.TrimStart();
            testWord.ToLower();
            // test word checker
            _correct = CheckWordArray("BALE");
        }
    }
    public bool CheckWordArray(string word)
    {
        // bool to check if word is found
        bool wordFound = false;
       
       
        Debug.Log("Word to look up +" + word + "+");
      

        // loop through the list of words
        for(int i = 0; i< _testWordArray.Length; i++)
        {
            Debug.Log("Test Word " + _testWordArray[i] + " = " + word);
            // check to see if words equal
            if(_testWordArray[i] == word)
            {
                Debug.Log("word found in array");
            }
        }
        {
          
        }
        // after loop if word is found return true
        if (wordFound == true)
        {
            return true;
        }
        // if word not found return false
        else
        {
            return false;
        }
       
    }

See how these print out on two lines? The first word (the one in the array) seems to have a newline at the end of it.

Unfortunately splitting via "\n"[0] does not strip off a "\r" if one happens to be at the end of the string.

https://stackoverflow.com/questions/1508203/best-way-to-split-string-into-lines

Would this be better, or do I have to scrap it completely

_wordList.AddRange(_wordListFileWholeThing.Split("\n\r"[0]));

As this is engineering, you’re welcome to try your own stuff out, let us know if it works. What you wrote above should not work any different, since you’re just passing the 0th character in, and ignoring the 1th character.

Alternatively if you just want to get this done and move forward, you might want to try one of the split options suggested in the stackoverflow post I linked above. :slight_smile:

1 Like

Thank you for your help. It is all sorted now, just a simple formatting error or the line space. In the end I just replaced the line space.