2016-11-28 56 views
-2

我有一个函数,它将采用string并删除它的第一个单词并始终保留最后一个单词。连续删除字符串中的第一个单词并保留最后一个单词[Xamarin Forms] C#

该字符串从我的函数SFSpeechRecognitionResult result返回。

使用我当前的代码,当代码运行一次时,第一个单词从字符串中删除,只剩下最后一个单词。但是当函数再次运行时,新添加的单词只会保持在result.BestTranscription.FormattedStringstring中,并且第一个单词不会被删除。

这是我的函数:

RecognitionTask = SpeechRecognizer.GetRecognitionTask 
(
    LiveSpeechRequest, 
    (SFSpeechRecognitionResult result, NSError err) => 
    { 
     if (result.BestTranscription.FormattedString.Contains(" ")) 
     { 
      //and this is where I try to remove the first word and keep the last 
      string[] values = result.BestTranscription.FormattedString.Split(' '); 
      var words = values.Skip(1).ToList(); 
      StringBuilder sb = new StringBuilder(); 
      foreach (var word in words) 
      { 
       sb.Append(word + " "); 
      } 

      string newresult = sb.ToString(); 
      System.Diagnostics.Debug.WriteLine(newresult); 
     } 
     else 
     { 
      //if the string only has one word then I will run this normally 
      thetextresult = result.BestTranscription.FormattedString.ToLower(); 
      System.Diagnostics.Debug.WriteLine(thetextresult); 
     } 
    } 
); 
+1

这可能是因为你总是在字符串的结尾添加一个空格,因此'.Contains(“”)'总是正确的?尝试'String.Join(“”,words)'而不是。 –

+1

为什么把这个保存为一个字符串而不是'List '个别的单词?或者甚至可能是'队列',因为这似乎是如何工作? – DavidG

+0

更快的方式是'串newresult = previousresult.Substring(previousresult.IndexOf(”“));' –

回答

1

我建议只取最后一个元素分割后:

string last_word = result.BestTranscription.FormattedString.Split(' ').Last(); 

这会给你总是硬道理

确保result.BestTranscription.FormattedString != null分裂之前,否则你会得到一个异常。

可能还有一个选项,可以在处理第一个字符串后清除字符串,以便始终只显示最后记录的字词。你可以尝试把它在这样的结尾复位:

result.BestTranscription.FormattedString = ""; 

基本上你的代码会是这个样子:

if (result.BestTranscription.FormattedString != null && 
    result.BestTranscription.FormattedString.Contains(" ")) 
{ 
    //and this is where I try to remove the first word and keep the last 
    string lastWord = result.BestTranscription.FormattedString.Split(' ')Last(); 

    string newresult = lastWord; 
    System.Diagnostics.Debug.WriteLine(newresult); 
} 
+0

非常感谢! :)对这个解决方案非常有用。 –

+0

@CarlosRodrigez很高兴我能帮上忙。 –

相关问题