2016-11-28 6 views
-2

私はstringを取り、その最初の単語を削除し、最後の単語を常に保持する関数を持っています。文字列内の最初の単語を連続して削除し、最後の単語を保持する[Xamarinフォーム] C#

文字列が私の関数SFSpeechRecognitionResult resultから返されます。

私の現在のコードでは、コードが1回実行され、最初の単語が文字列から削除され、最後の単語だけが残されます。しかし、関数が再び実行されると、新しく追加された単語は、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 'ではなく、これを文字列として保存しますか?または、おそらく 'Queue 'のように動作しているようです。 – 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私は助けることができてうれしい。 –

関連する問題