【问题标题】:Remove the first word in a string continuously and keep the last word [Xamarin Forms] C#连续删除字符串中的第一个单词并保留最后一个单词 [Xamarin Forms] C#
【发布时间】:2016-11-28 21:36:46
【问题描述】:

我有一个函数,它将采用 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);
        }
    }
);

【问题讨论】:

  • 这可能是因为您总是在字符串末尾附加一个空格,因此.Contains(" ") 总是正确的?请改用String.Join(" ", words)。
  • 为什么将其保留为字符串而不是单个单词的List<string>?或者甚至可能是Queue<string>,因为它似乎是这样工作的?
  • 更快的方法是string newresult = previousresult.Substring(previousresult.IndexOf(" "));
  • 如果我这样做:if (howmanyTimesUsed == 0) { howmanyTimesUsed = howmanyTimesUsed + 1; thetextresult = result.BestTranscription.FormattedString.ToLower(); resultCallback(thetextresult); } else { string newresult = result.BestTranscription.FormattedString.Substring (result.BestTranscription.FormattedString.IndexOf(" ")); resultCallback(newresult); } 字符串仍然不断添加单词而不会被删除
  • 注意到我得到了很多反对意见 :( 是因为我没有显示足够的代码吗?

标签: c# string xamarin xamarin.forms speech-recognition


【解决方案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);
}

【讨论】:

  • @CarlosRodrigez 很高兴我能提供帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-18
  • 1970-01-01
  • 2018-03-27
  • 2023-02-03
  • 2021-12-14
  • 1970-01-01
相关资源
最近更新 更多