在foreach(单词中的字符串单词)中,如果(if->true)C#,我怎么能转到下一个单词

本文关键字:单词 true 怎么能 下一个 if- 字符串 foreach 如果 单词中 | 更新日期: 2023-09-27 18:37:22

这个想法是他输入一个文本文件和一个单词数字。该软件将在一个新文件中写入该文本,但每行包含单词数(他输入的),以及其他一些细节。

我的想法是这样的,我把他列入了黑名单。黑名单从文件加载到富箱中,并在关闭应用程序时保存。

问题是我已经设置了所有内容(一个检查单词是否在黑框中的功能)。

该软件看起来像这样:

foreach (string word in words)
{
     int blacklist = 0;
     if (FindMyText(word))
     {
           blacklist = 1;
           MessageBox.Show("Current word: " + word + " is blacklisted!");
     }
     else
           MessageBox.Show("Word: " + word);               
     // the code here ... for writing in file and all that
     }

函数FindMyText(word)告诉我该单词是否在黑名单中。

如果该函数返回 true,我想进入下一个单词,但真的不知道该怎么做。

如果你有一些想法,真的会帮助我。

谢谢你们。

在foreach(单词中的字符串单词)中,如果(if->true)C#,我怎么能转到下一个单词

在 foreach 循环或任何其他循环中,您可以使用continue跳到下一次迭代,因此在您的情况下您可以这样做

foreach (string word in words)
{
  var blacklist = 0;
  if (FindMyText(word))
  {
    blacklist = 1;
    MessageBox.Show("Current word: " + word + " is blacklisted!");
    continue;
  } else {
     //...
  }
 }

您可以添加"继续"键来跳到foreach迭代中的下一个元素。

foreach (string word in words)
{
    int blacklist = 0;
    if (FindMyText(word))
    {
        blacklist = 1;
        MessageBox.Show("Current word: " + word + " is blacklisted!");
        // skip to the next element
        continue;
    }
    MessageBox.Show("Word: " + word);
    // the code here ... for writing in file and all that
}

或者你可以直接拆分 foreach 身体:

foreach (string word in words)
{
    int blacklist = 0;
    if (FindMyText(word))
    {
        blacklist = 1;
        MessageBox.Show("Current word: " + word + " is blacklisted!");
    }
    else
    {
        MessageBox.Show("Word: " + word);
        // the code here ... for writing in file and all that
    }
}

这完全取决于"其他"部分有多长。如果它真的很长,使用继续,将重点放在跳过部分上,则更具可读性。

你已经有了逻辑,只需添加continue

continue 语句将控制权传递给它所在的封闭迭代语句的下一个迭代。它采用以下形式:

if (FindMyText(word))
{
  blacklist = 1;
  MessageBox.Show("Current word: " + word + " is blacklisted!");
  continue;
}
else
{
   MessageBox.Show("Word: " + word);
  AddWordToFile(word); // not black listed;
}

http://msdn.microsoft.com/en-US/library/923ahwt1(v=vs.71).aspx

我不是 100% 确定我理解,但我认为你想要的是"继续"关键字。

循环的迭代完成后,它将再次开始,直到迭代用完。

所以在你的IF/Else语句中,你想强制循环进入下一个单词,你键入继续;。这将忽略循环中的所有上述代码,并跳转到下一个迭代。

这有意义吗?