Looks like the actual question is how to reverse words in a string using recursion. Phrasing the question correctly is often 50% of actually solving it. Googling for reverse words with recursion
returns several answers that show this is not an easy thing to do.
It requires two steps - one going forward to find the word boundaries and then one that backtracks to reverse the already identified word. I assume the point is to avoid loops entirely, so trying to find spaces using IndexOf
is out of scope.
Reversing is easy - in fact the original code can be simplified a lot:
string Rev(string input)
{
if (input.Length==0)
{
return input;
}
return Rev(input.Substring(1)) + input[0];
}
The problem with this function is that strings are immutable and every string operation allocates a new string that needs to be garbage-collected. It would be better to use Array.Reverse
on the character array for this.
The second step is to find the words and transfer them from one call to the next. This similar question uses a stack to transfer the words, while this question splits a string into a head/tail when a space is discovered. The techniques can be combined, but instead of a stack we can use a string. Again, this wastes memory because it creates temporary strings.
string Rev(string input)
{
if (input.Length==0)
{
return input;
}
return Rev(input.Substring(1)) + input[0];
}
string Word(string words,string head,string tail)
{
//Finished, return the final string.
if(tail.Length==0)
{
return (words.Length==0)? Rev(head): words + " " + Rev(head);
}
//Word boundary found
if (tail[0]==' ')
{
//Add the revesed word to the words
words=(words.Length==0)? Rev(head): words + " " + Rev(head);
head="";
tail=tail.Substring(1);
}
//No boundary, just copy one character from the tail to the head
else
{
head=head + tail[0];
tail=tail.Substring(1);
}
return Word(words,head,tail);
}
Calling Word("","","Hello World Boo Soo")
will return olleH dlroW ooB ooS
.
Again, this is very wasteful.