Skip to content
Related Articles

Related Articles

Program to reverse words in a given string in C++

Improve Article
Save Article
  • Difficulty Level : Medium
  • Last Updated : 11 Jul, 2022
Improve Article
Save Article

Given a sentence in the form of string str, the task is to reverse each word of the given sentence in C++. 
Examples: 
 

Input: str = “the sky is blue” 
Output: blue is sky the
Input: str = “I love programming” 
Output: programming love I 
 

 

Method 1: Using STL functions 
 

  1. Reverse the given string str using STL function reverse().
  2. Iterate the reversed string and whenever a space is found reverse the word before that space using the STL function reverse().

Below is the implementation of the above approach:
 

CPP




// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to reverse the given string
string reverseString(string str)
{
 
    // Reverse str using inbuilt function
    reverse(str.begin(), str.end());
 
    // Add space at the end so that the
    // last word is also reversed
    str.insert(str.end(), ' ');
 
    int n = str.length();
 
    int j = 0;
 
    // Find spaces and reverse all words
    // before that
    for (int i = 0; i < n; i++) {
 
        // If a space is encountered
        if (str[i] == ' ') {
            reverse(str.begin() + j,
                    str.begin() + i);
 
            // Update the starting index
            // for next word to reverse
            j = i + 1;
        }
    }
 
    // Remove spaces from the end of the
    // word that we appended
    str.pop_back();
 
    // Return the reversed string
    return str;
}
 
// Driver code
int main()
{
    string str = "I like this code";
 
    // Function call
    string rev = reverseString(str);
 
    // Print the reversed string
    cout << rev;
    return 0;
}

Output

code this like I

Time Complexity: O(n2

Auxiliary Space: O(1)

Method 2: Without using the inbuilt function: We can create the reverse() function which is used to reverse the given string. Below are the steps: 
 

  1. Initially reverse each word of the given string str.
  2. Now reverse the whole string to get the resultant string in desired order.

Below is the implementation of the above approach:
 

CPP




// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function used to reverse a string
// from index l to r
void reversed(string& s, int l, int r)
{
 
    while (l < r) {
 
        // Swap characters at l and r
        swap(s[l], s[r]);
        l++;
        r--;
    }
}
 
// Function to reverse the given string
string reverseString(string str)
{
 
    // Add space at the end so that the
    // last word is also reversed
    str.insert(str.end(), ' ');
 
    int n = str.length();
 
    int j = 0;
 
    // Find spaces and reverse all words
    // before that
    for (int i = 0; i < n; i++) {
 
        // If a space is encountered
        if (str[i] == ' ') {
 
            // Function call to our custom
            // reverse function()
            reversed(str, j, i - 1);
 
            // Update the starting index
            // for next word to reverse
            j = i + 1;
        }
    }
 
    // Remove spaces from the end of the
    // word that we appended
    str.pop_back();
 
    // Reverse the whole string
    reversed(str, 0, str.length() - 1);
 
    // Return the reversed string
    return str;
}
 
// Driver code
int main()
{
    string str = "I like this code";
 
    // Function call
    string rev = reverseString(str);
 
    // Print the reversed string
    cout << rev;
    return 0;
}

Output

code this like I

Time Complexity: O(n2
Auxiliary Space: O(1) 

Method – 3 : Without Using Extra Space

The above task can also be accomplished by splitting and directly swapping the string starting from the middle. As direct swapping is involved, less space is consumed too.

C++




// C++ code to reverse a string
#include <bits/stdc++.h>
using namespace std;
 
// Reverse the string
string RevString(string s[], int l)
{
    // Check if number of words is even
    if (l % 2 == 0) {
        // Find the middle word
        int j = l / 2;
 
        // Starting from the middle
        // start swapping words at
        // jth position and l-1-j position
        while (j <= l - 1) {
            string temp;
            temp = s[l - j - 1];
            s[l - j - 1] = s[j];
            s[j] = temp;
            j += 1;
        }
    }
 
    // Check if number of words is odd
    else {
        // Find the middle word
        int j = (l / 2) + 1;
 
        // Starting from the middle start
        // swapping the words at jth
        // position and l-1-j position
        while (j <= l - 1) {
            string temp;
            temp = s[l - j - 1];
            s[l - j - 1] = s[j];
            s[j] = temp;
            j += 1;
        }
    }
 
    string S = s[0];
 
    // Return the reversed sentence
    for (int i = 1; i < 9; i++) {
        S = S + " " + s[i];
    }
    return S;
}
 
// Driver code
int main()
{
    string s = "getting good at coding "
               "needs a lot of practice";
 
    string words[]
        = { "getting", "good", "at", "coding""needs",
            "a",       "lot""of", "practice" };
 
    cout << RevString(words, 9) << endl;
    return 0;
}
 
// This code is contributed by AJAY MAKVANA

Output

practice of lot a needs coding at good getting

Time Complexity: O(n) 

Auxiliary Space: O(n)


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!