Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Search string in array

Discussion in 'Getting Started' started by Tpleme, Nov 21, 2019.

  1. Tpleme

    Tpleme

    Joined:
    May 10, 2019
    Posts:
    7
    Hello everyone,

    I've been working around this for to long.

    I have this code to search for a specific string from an array.

    This array gets its values from a txt file:
    Each word in the txt file is separated by a new line;

    Code (CSharp):
    1. public InputField enterNameField;
    2. public TextAsset badWordsFile;
    3. string[] badwords = badWordsFile.text.Split('\n');
    With that a creat a string named "WordToSearch", that is the text fomr the inputfield

    Code (CSharp):
    1. string wordToSearch = enterNameField.text;
    Code (CSharp):
    1. if (badwords.Any(wordToSearch.ToLower().Contains))
    2.         {
    3.             print("Word Found:  " + wordToSearch);
    4.  
    5.         }
    6.         else
    7.         {
    8.             print("No word found");
    9.  
    10.         }
    The issue is that this returns true all the time, no matter what is in the inputflied.

    I already tried
    Code (CSharp):
    1. if (badwords.Contains(wordToSearch))
    Code (CSharp):
    1. badwords.All(wordToSearch.ToLower()
    but noting seems to work.

    Can anyone help me identify the issue here?

    Thank you
     
    eXonius likes this.
  2. Joe-Censored

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    11,847
    array.Any and array.All take a LINQ Predicate as input, which you're not doing. Either use a Predicate or just loop through the array the old fashioned way. (Google how to write a LINQ Predicate for more info)

    Code (csharp):
    1. bool naughtyWord = false;
    2. foreach (string word in badwords)
    3. {
    4.     if (word == wordToSearch.ToLower())
    5.     {
    6.         naughtyWord = true;
    7.     }
    8. }
     
    JoeStrout likes this.
  3. Tpleme

    Tpleme

    Joined:
    May 10, 2019
    Posts:
    7
    thank you for the reply, gonna check how linq work, better learn it from the ground.

    regards