Carlos Rodrigez Carlos Rodrigez - 5 days ago 6
C# Question

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

I have a function that will take a string and remove its first word and always keep the last word.

The string gets returned from my function

SFSpeechRecognitionResult result
.

With my current code it works when the code runs once, the first word gets deleted from the string and only the last word is left. But when the function runs again then the newly added words to the string just keeps stacking up and the first word does not get removed.

This is my function:

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

Answer

I would suggest to just take the last element after splitting:

string last_word = result.BestTranscription.FormattedString.Split(' ').Last();

This will give you always the last word

make sure that result.BestTranscription.FormattedString != null before splitting otherwise you get an exception.

May be there is also an option to clear the string of words after the processing of the first, so that you always get only the word that is recorded last. You could try to reset it at the end like this:

result.BestTranscription.FormattedString = "";

Basically your code would look something like this:

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