Reverse words in a given string | Set 2

Given a string str, the task is to reverse the string by considering each word of the string, str as a single unit.
Examples:

Input: str = “geeks quiz practice code”
Output: code practice quiz geeks 
Explanation: 
The words in the given string are [“geeks”, “quiz”, “practice”,  “code”]. 
Therefore, after reversing the order of the words, the required output is“code practice quiz geeks”.

Input: str = “getting good at coding needs a lot of practice”
Output: practice of lot a needs coding at good getting

In-place Reversal Approach: Refer to the article Reverse words in a given string for the in-place reversal of words followed by a reversal of the entire string. 

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

Stack-based Approach: In this article, the approach to solving the problem using Stack is going to be discussed. The idea here is to push all the words of str into the Stack and then print all the elements of the Stack. Follow the steps below to solve the problem:

  1. Create a Stack to store each word of the string str.
  2. Iterate over string str, and separate each word of str by a space delimiter.
  3. Push all the words of str into the stack.
  4. Print all the elements of the stack one by one.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ Program to implememnt
// the above approach
  
#include <bits/stdc++.h>
using namespace std;
  
// Function to reverse the words
// of a given string
void printRev(string str)
{
    // Stack to store each
    // word of the string
    stack<string> st;
  
    // Store the whole string
    // in string stream
    stringstream ss(str);
  
    string temp;
    while (getline(ss, temp, ' ')) {
  
        // Push each word of the
        // string into the stack
        st.push(temp);
    }
  
    // Print the string in reverse
    // order of the words
    while (!st.empty()) {
        cout << st.top() << " ";
        st.pop();
    }
}
  
// Driver Code
int main()
{
    string str;
    str = "geeks quiz practice code";
  
    printRev(str);
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java Program to implememnt
// the above approach
import java.util.*;
class GFG{
  
    // Function to reverse the words
    // of a given String
    static void printRev(String str)
    {
        // Stack to store each
        // word of the String
        Stack<String> st = new Stack<String>();
  
        // Store the whole String
        // in String stream
        String[] ss = str.split(" ");
  
        for (String temp : ss) 
        {
  
            // Push each word of the
            // String into the stack
            st.add(temp);
        }
  
        // Print the String in reverse
        // order of the words
        while (!st.isEmpty()) 
        {
            System.out.print(st.peek() + " ");
            st.pop();
        }
    }
  
    // Driver Code
    public static void main(String[] args)
    {
        String str;
        str = "geeks quiz practice code";
        printRev(str);
    }
}
  
// This code is contributed by Rajput-Ji

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to implememnt
# the above approach
  
# Function to reverse the words
# of a given strring
def printRev(strr):
      
    # Stack to store each
    # word of the strring
    strr = strr.split(" ")
    st = []
  
    # Store the whole strring
    # in strream
    for i in strr:
  
        # Push each word of the
        # into the stack
        st.append(i)
  
    # Print the in reverse
    # order of the words
    while len(st) > 0:
        print(st[-1], end = " ")
        del st[-1]
  
# Driver Code
if __name__ == '__main__':
      
    strr = "geeks quiz practice code"
      
    printRev(strr)
  
# This code is contributed by mohit kumar 29

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to implememnt
// the above approach
using System;
using System.Collections; 
  
class GFG{
  
// Function to reverse the words
// of a given String
static void printRev(string str)
{
      
    // Stack to store each
    // word of the String
    Stack st = new Stack();
  
    String[] sepearator = {" "}; 
      
    // Store the whole String
    // in String stream
    string[] ss = str.Split(sepearator,
                            int.MaxValue,
             StringSplitOptions.RemoveEmptyEntries);
  
    foreach(string temp in ss) 
    {
  
        // Push each word of the
        // String into the stack
        st.Push(temp);
    }
  
    // Print the String in reverse
    // order of the words
    while (st.Count > 0) 
    {
        Console.Write(st.Peek() + " ");
        st.Pop();
    }
}
  
// Driver Code
public static void Main(string[] args)
{
    string str;
    str = "geeks quiz practice code";
      
    printRev(str);
}
}
  
// This code is contributed by rutvik_56

chevron_right


Output: 

code practice quiz geeks

Time Complexity: O(N), where N denotes the length of the string.
Auxiliary Space: O(N)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.