2016-11-28 55 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很高興我能幫上忙。 –

相關問題