Hello everyone. I have been asked to reverse a sentence using recursion. Below is what I have managed to do so far, but now I am at a dead end. I can't seem to get my code to do what I want...
the final string should read
"Peppers Pickled of Peck a Picked Piper Peter"
I get
"sreppeP delkciP fo kceP a dekciP repiP reteP"
As you can see it is reversed - kind of. So it has got me thinking... I need to extract each word from the reversed string and then pass it to my recursion function to reverse again?
Any help is welcome!!
Put your text in an istringstream. Call reverse on that istringstream.
In the function reverse:
- try to read a word from the stream; return immediately if this fails
- call reverse with the remaining stringstream (this is the recursion)
- output the word.
Well that's unfortunate; std::string is the C++ way to do all this sort of thing. Messing around with arrays of char is awkward and error prone and essentially C code; not just in syntax, but in ways of thinking. Thinking in C is a common mistake newcomers to C++ make; I suspect that in such cases, people are actually being taught C, with a couple of extra bits on top, rather than being taught C++.
If you insist on doing this in C, you're going to have to write a function to extract an entire word from the sentence. Do you have to do this in C, or can you use std::string and other basics of C++? I see you're happy to use std::swap so clearly you're using some C++ basics.
Thanks for the reply. I have done it that way simply to get the recursion bit to work. Thinking on I can convert to C++ strings, get the recursion function to work first. Then maybe use find_first_of for the spaces and extract each word, reverse each word then += to my final string?
#include <iostream>
#include <string>
usingnamespace std;
string reverseSentence(string input)
{
// No more sentence? Just return empty string
if (input.size() == 0) {return string();}
string nextWord;
// Trim space off the front of the string before getting my word
while (input.size() != 0 &&
input[0] == ' ')
{
input.erase(input.begin());
}
// Get my word by grabbing letters until there's no more letters or hit space
while (input.size() != 0 &&
input[0] != ' ' )
{
nextWord+=input[0];
input.erase(input.begin());
}
return (reverseSentence(input) + ' ' + nextWord);
}
int main() {
string testString("Peter Piper Picked a Peck of Pickled Peppers");
cout << reverseSentence(testString);
// your code goes here
return 0;
}
Hi lastchance - thanks for your help.
I need a bit of help understanding reverse and how it works.
p is set to first instance of white space in string.
p is not = npos so skips over.
reverse is called again with a substring of s starting at p + 1.
it then continues until npos. Forgive my ignorance but how does the cost tie in at the end & is it possible to return a string from this function...