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



我有一个函数,它将取一个string,删除它的第一个字,并始终保留最后一个字。

字符串从我的函数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);
}
}
);

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

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

最新更新