reversing words

Hi Guys,

I'm doing an online course in C++ (beginners)

I've been tasked with reversing certain words in a string.

I just wanted to ask your advice on what the best way of doing this would be, as I'm struggling a little bit.

To be more clear, I have to reverse every other word in a sentence, any suggestions are welcome.

Thanks.
Last edited on
Several approaches:
a) Read word from input sentence, reverse it, and add to outpus tentence
1
2
3
4
5
6
7
8
9
10
11
//mock-up code
string input;
istringstream in(input);
ostringstream out;
string word;
while(in >> word)
{
    reverse(word);
    out << word;
}
return out.str();

b) Store words boundaries in container then reverse words.
1
2
3
4
5
//mock-up code
vector<pair<char*, char*>> words;
words = get_words(input);
for(auto word: words)
    reverse(word.first, word.second)
Thanks for the swift reply MiiNiPaa, I know it must be frustrating for someone skilled like yourself, but is there perhaps a way you could explain a little more?

I have basic c++ knowledge and I know that I have to use substrings (so I have read at least)
I am trying to reverse every other word in the sentence, eg-

"The mouse was caught in the peg"

So "mouse" "caught" "the" would need to be reversed and then output into the full sentence but with the even words reversed, if there are any tutorials etc I would be happy to follow them.

Thanks again.
If your sentence does not contain punctuation and word are separated by single space, this will suffice:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <sstream>
#include <iostream>
#include <algorithm>
#include <string>

int main()
{
    std::string original = "The mouse was caught in the peg";
    //http://en.cppreference.com/w/cpp/io/basic_istringstream/basic_istringstream
    std::istringstream in(original);
    std::ostringstream out;
    std::string word;
    int i = 0;
    while(in >> word) {//Read next word in sentence
        ++i;
        if(i % 2 == 0) //on each even word
            //http://en.cppreference.com/w/cpp/algorithm/reverse
            std::reverse(word.begin(), word.end()); //reverse word
        out << word << ' '; //Add word to new sentence
    }
    std::string modified = out.str();
    std::cout << original << '\n' << modified;
}
The mouse was caught in the peg
The esuom was thguac in eht peg
Ah it makes much more sense now! Thanks for the reply! Finally how would I go about modifying it so that the user could input the sentence rather than hard coded?
1
2
3
4
5
int main()
{
    std::string original = "The mouse was caught in the peg";
    std::getline(std::cin >> std::ws, original);
    //... 
Last edited on
Thanks alot for your help! :)
Topic archived. No new replies allowed.