Search code examples
c++recursion

Reverse word order in sentence


I'm having difficulty creating a function that reverse the order of the sentence around. I've read many functions on how to recursively reverse the letters around and I have successfully done so, but I do not want to reverse the letters in the words. I want to reverse the placement of the words in the sentence.

Example would be:

This is a sentence.

sentence. a is This

This is my code so far. How do I go from reversing order of letters of the entire sentence to placement order of words in a sentence?

The output of the current code would provide: !dlroW olleH

void reverse(const std::string str)
{
    int length = str.size();
    if(length > 0)
    {
        reverse(str.substr(0,length-1));
        std::cout << str[0];

    }
}

Edit: Additional question. If this was a char array would the logic be different?


Solution

  • // Pass string which comes after space
    // reverse("This is a sentence.") 
    // reverse("is a sentence.") 
    // reverse("a sentence.") 
    // reverse("sentence.") 
    // will not find space 
    // start print only word in that function
    
    void reverse(const std::string str)
    {
        int pos = str.find_first_of(" ");
        if (pos == string::npos) // exit condition
        {
            string str1 = str.substr(0, pos);
            cout << str1.c_str() << " " ;
            return;
        }
    
        reverse(str.substr(pos+1));
        cout << str.substr(0, pos).c_str() << " ";
    }
    

    Simple to understand:

    void reverse(const std::string str)
    {
        int pos = str.find_first_of(" ");
        if (pos != string::npos) // exit condition
        {
            reverse(str.substr(pos + 1));
        }
        cout << str.substr(0, pos).c_str() << " ";
    }