如何停止string.Contains()挑选另一个单词中的单词.下面更好的解释

Luk*_*ood 0 c# string contains

我在我的程序中使用语音识别并且比写出每个可能的单词组合来执行某个命令更容易,我使用.Contains函数来挑选某些关键字.例...

private void SpeechHypothesized(object sender, SpeechHypothesizedEventArgs e)
{
    string speech = e.Result.Text;

    if (speech.Contains("next") && speech.Contains("date"))
    {
        MessageBox.Show(speech + "\nThe date will be the 11th");
    }
    else if (speech.Contains("date"))
    {
        MessageBox.Show(speech + "\nThe date is the 10th");
    }
}
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,如果语音被略微识别,它将显示一个文本框,说出它假设的内容,然后是日期.但是,当我查看文本框中显示的语音时,它会显示"下次更新"之类的内容.因此,该程序正在寻找另一个词,即"更新"内的"日期".我不希望这种情况发生,否则它就不会那么准确,怎么能让.Contains方法自己选出单词,而不是查看其他单词呢?谢谢

Sam*_*Sam 6

替代解决方案,拆分所有空格并检查关键字

string speech_text = e.Result.Text;
string[] speech = speech_text.Split();

if (speech.Contains("next") && speech.Contains("date"))
{
    MessageBox.Show(speech_text + "\nThe date will be the 11th");
}
else if (speech.Contains("date"))
{
    MessageBox.Show(speech_text + "\nThe date is the 10th");
}
Run Code Online (Sandbox Code Playgroud)

  • IMO这比使用正则表达式更简单. (2认同)