连续删除字符串中的第一个单词并保留最后一个单词[Xamarin Forms] C#

Remove the first word in a string continuously and keep the last word [Xamarin Forms] C#

我有一个函数可以接受 string 并删除它的第一个词并始终保留最后一个词。

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

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

这是我的功能:

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);
        }
    }
);

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

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);
}