Reverse words in a given string | Set 2 - GeeksforGeeks

26 Sep, 2021
Given 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:
Create a Stack to store each word of the string str.Iterate over string str, and separate each word of str by a space delimiter.Push all the words of str into the stack.Print all the elements of the stack one by one.
Create a Stack to store each word of the string str.
Iterate over string str, and separate each word of str by a space delimiter.
Push all the words of str into the stack.
Print all the elements of the stack one by one.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ Program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to reverse the words// of a given stringvoid 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 Codeint main(){    string str;    str = "geeks quiz practice code";     printRev(str);    return 0;}
// Java Program to implement// the above approachimport 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
# Python3 program to implement# the above approach # Function to reverse the words# of a given stringdef printRev(strr):         # Stack to store each    # word of the string    strr = strr.split(" ")    st = []     # Store the whole string    # in stream    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 Codeif __name__ == '__main__':         strr = "geeks quiz practice code"         printRev(strr) # This code is contributed by mohit kumar 29
// C# program to implement// the above approachusing System;using System.Collections; class GFG{ // Function to reverse the words// of a given Stringstatic void printRev(string str){         // Stack to store each    // word of the String    Stack st = new Stack();     String[] separator = {" "};         // Store the whole String    // in String stream    string[] ss = str.Split(separator,                            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 Codepublic static void Main(string[] args){    string str;    str = "geeks quiz practice code";         printRev(str);}} // This code is contributed by rutvik_56
<script>// Javascript Program to implement// the above approach // Function to reverse the words// of a given Stringfunction printRev(str){        // Stack to store each        // word of the String        let st = [];          // Store the whole String        // in String stream        let ss = str.split(" ");          for (let temp=0;temp< ss.length;temp++)        {              // Push each word of the            // String into the stack            st.push(ss[temp]);        }          // Print the String in reverse        // order of the words        while (st.length!=0)        {            document.write(st.pop() + " ");                     }} // Driver Codelet str;str = "geeks quiz practice code";printRev(str);  // This code is contributed by unknown2108</script>
code practice quiz geeks 
Time Complexity: O(N), where N denotes the length of the string.Auxiliary Space: O(N)
As all the words in a sentence are separated by spaces.
We have to split the sentence by spaces using split().
We split all the words by spaces and store them in a list.
Reverse this list and print it.
C++
Java
Python3
C#
Javascript
// C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Function to reverse the words// of a given stringvoid printRev(string lis[]){       // reverse the list    reverse(lis, lis + 4);          for(int i = 0; i < 4; i++)    {        cout << lis[i] << " ";    }}     int main(){    string strr[] = {"geeks", "quiz", "practice", "code"};       printRev(strr);     return 0;} // This code is contributed by divyeshrabadiya07.
// Java program to implement// the above approachimport java.util.*; class GFG{     // Function to reverse the words// of a given stringstatic void printRev(String string){         // Split by space and converting    // string to list    String[] lis = string.split(" ", 0);          // Reverse the list    Collections.reverse(Arrays.asList(lis));          // Printing the list    for(String li : lis)    {        System.out.print(li + " ");    }} // Driver codepublic static void main(String[] args){    String strr = "geeks quiz practice code";     printRev(strr);}} // This code is contributed by decode2207
# Python3 program to implement# the above approach # Function to reverse the words# of a given string  def printRev(string):    # split by space and converting    # string to list    lis = list(string.split())    # reverse the list    lis.reverse()    # printing the list    print(*lis)  # Driver Codeif __name__ == '__main__':     strr = "geeks quiz practice code"     printRev(strr) # This code is contributed by vikkycirus
// C# program to implement// the above approachusing System;class GFG {         // Function to reverse the words    // of a given string    static void printRev(string String)    {        // split by space and converting        // string to list        string[] lis = String.Split(' ');                 // reverse the list        Array.Reverse(lis);                 // printing the list        foreach(string li in lis)        {            Console.Write(li + " ");        }    }   static void Main() {    string strr = "geeks quiz practice code";      printRev(strr);  }} // This code is contributed by rameshtravel07.
<script> // javascript program to implement// the above approach // Function to reverse the words// of a given string  function printRev(string){    // split by space and converting    // string to list    var lis = string.split(' ');    console.log(lis);    // reverse the list    lis.reverse();    console.log(lis);       // printing the list    document.write(lis.join(' '));}     // Driver Code     var strr = "geeks quiz practice code"     printRev(strr) </script>
code practice quiz geeks
mohit kumar 29
Rajput-Ji
rutvik_56
vikkycirus
adnanirshad158
bunnyram19
unknown2108
ruhelaa48
saurabh1990aror
rameshtravel07
decode2207
divyeshrabadiya07
anikaseth98
Reverse
substring
Stack
Strings
Strings
Stack
Reverse
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Real-time application of Data Structures
ZigZag Tree Traversal
Reverse individual words
Evaluation of Prefix Expressions
Sort a stack using a temporary stack
Write a program to reverse an array or string
Reverse a string in Java
Write a program to print all permutations of a given string
C++ Data Types
Longest Common Subsequence | DP-4