【问题标题】:checking if textbox contains a word not working [closed]检查文本框是否包含一个不起作用的单词[关闭]
【发布时间】:2018-09-10 00:52:27
【问题描述】:

它似乎只检测/检查列表中的第一个单词。

private bool ContentCheck()
    {
        List<string> FilteredWords = new List<string>()
        {
            "duck",
            "donkey",
            "horse",
            "goat",
            "dog",
            "cat",                  //list of censored words
            "lion",
            "tiger",
            "bear",
            "crocodile",
            "eel",
        };
        foreach (var e in FilteredWords)
        {
            if (memoEdit1.Text.Contains(e))
            {
                return true; 
            }
            else
            {
                return false;
            }
        }
        return false;
    }

 private void button_click (object sender, EventArgs e)

  {

   if (ContentCheck() == false)
   {
                    //do something
   }

   else if (ContentCheck() == true)
   {
     MessageBox.Show("Error: Offensive word.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
   }
 }

【问题讨论】:

    标签: c# list foreach textbox contains


    【解决方案1】:

    foreach 块内的if 语句中的两种情况都会导致return。想一想,程序将迭代列表中的第一项,如果是脏话它会返回,如果不是它也会返回。这两个都将退出代码,因此永远不会迭代下一个项目。

    要解决此问题,您需要进行更改

    foreach (var e in FilteredWords)
    {
        if (memoEdit1.Text.Contains(e))
        {
            return true; 
        }
        else
        {
            return false;
        }
    }
    return false;
    

    foreach (var e in FilteredWords)
    {
        if (memoEdit1.Text.Contains(e))
        {
            return true; 
        }
    }
    return false;
    

    【讨论】:

    • 哦,哈哈,谢谢,这是我第一次使用 bools,哈哈。
    猜你喜欢
    • 1970-01-01
    • 2011-11-08
    • 2012-03-26
    • 2023-04-01
    • 2023-04-08
    • 1970-01-01
    • 1970-01-01
    • 2014-05-18
    • 2019-05-29
    相关资源
    最近更新 更多