I need to transform a string such as "my name is thomos" to "ym eman si somoht". What do I need to know in order to do that?
Use strtok to split into words For each word, reverse the string and append to the output, along with a space
One possibility would be to use std::copy
with a pair of std::reverse_iterator
s, which you can get with rbegin
and rend
.
Along with that, you'll probably want to use something like an std::istringstream
to break the string up into words for processing.
I will not provide code, as this smells too much like homework. But I'll try to give you a nudge into the right direction.
You will first have to chop the sentence into words. You can do this by reading it from a stream (a string stream will do if you happen to have it in a string) into a string using operator>>(std::istream&,std::string&)
.
Then you have to reverse the individual strings. You can do so using std::reverse()
from the C++ standard library.
Then all you have to do is to write the words to some output stream, putting spaces in between.
Alternatively you could output the word strings reversed, as Jerry suggested.
If you are coming at this from a c-style string point of view (as I had to the first time I did this problem for homework) you might want to try some pointers. Here is the basic order of operations I went through. If you are using std::string I am pretty sure this won't work, but it might. This is really meant for c-style strings and teaching people to use pointers.
Create 2 pointers and a temp swap char.
Increment the second pointer until it references a null terminating character. Promptly deincrement it by one.
Swap what the first pointer references with what the second one references until the pointers met or pass.