Given string str consisting of multiple words, the task is to reverse the entire string word by word.
Examples:
Input: str = “I Love To Code”
Output: Code To Love I
Input: str = “data structures and algorithms”
Output: algorithms and structures data
Approach: This problem can be solved not only with the help of the strtok() but also it can be solved by using Stack Container Class in STL C++ by following the given steps:
- Create an empty stack.
- Traverse the entire string, while traversing add the characters of the string into a temporary
variable until you get a space(‘ ‘) and push that temporary variable into the stack. - Repeat the above step until the end of the string.
- Pop the words from the stack until the stack is not empty which will be in reverse order.
Below is the implementation of the above approach:
C++
//C++ implementation of the above approach#include<bits/stdc++.h>using namespace std;//function to reverse the words//of the given string without using strtok().void reverse(string s){ //create an empty string stack stack<string> stc; //create an empty temporary string string temp=""; //traversing the entire string for(int i=0;i<s.length();i++) { if(s[i]==' ') { //push the temporary variable into the stack stc.push(temp); //assigning temporary variable as empty temp=""; } else { temp=temp+s[i]; } } //for the last word of the string stc.push(temp); while(!stc.empty()) { // Get the words in reverse order temp=stc.top(); cout<<temp<<" "; stc.pop(); } cout<<endl;}//Driver codeint main(){ string s="I Love To Code"; reverse(s); return 0;}// This code is contributed by Konderu Hrishikesh. |
Java
//Java implementation of// the above approachimport java.util.*;class GFG{// Function to reverse the words// of the given String without// using strtok().static void reverse(String s){ // Create an empty String stack Stack<String> stc = new Stack<>(); // Create an empty temporary String String temp = ""; // Traversing the entire String for(int i = 0; i < s.length(); i++) { if(s.charAt(i) == ' ') { // Push the temporary // variable into the stack stc.add(temp); // Assigning temporary // variable as empty temp = ""; } else { temp = temp + s.charAt(i); } } // For the last word // of the String stc.add(temp); while(!stc.isEmpty()) { // Get the words in // reverse order temp = stc.peek(); System.out.print(temp + " "); stc.pop(); } System.out.println();}//Driver codepublic static void main(String[] args){ String s = "I Love To Code"; reverse(s);}}// This code is contributed by gauravrajput1 |
Python3
# Python3 implementation of# the above approach# function to reverse the# words of the given string# without using strtok().def reverse(s): # create an empty string # stack stc = [] # create an empty temporary # string temp = "" # traversing the entire string for i in range(len(s)): if s[i] == ' ': # push the temporary variable # into the stack stc.append(temp) # assigning temporary variable # as empty temp = "" else: temp = temp + s[i] # for the last word of the string stc.append(temp) while len(stc) != 0: # Get the words in reverse order temp = stc[len(stc) - 1] print(temp, end = " ") stc.pop() print()# Driver codes = "I Love To Code"reverse(s)# This code is contributed by divyeshrabadiya07 |
C#
// C# implementation of// the above approachusing System;using System.Collections;class GFG{ // Function to reverse the words // of the given String without // using strtok(). static void reverse(string s) { // Create an empty String stack Stack stc = new Stack(); // Create an empty temporary String string temp = ""; // Traversing the entire String for(int i = 0; i < s.Length; i++) { if(s[i] == ' ') { // Push the temporary // variable into the stack stc.Push(temp); // Assigning temporary // variable as empty temp = ""; } else { temp = temp + s[i]; } } // For the last word // of the String stc.Push(temp); while(stc.Count != 0) { // Get the words in // reverse order temp = (string)stc.Peek(); Console.Write(temp + " "); stc.Pop(); } Console.WriteLine(); } // Driver code static void Main() { string s = "I Love To Code"; reverse(s); }}// This code is contributed by divyesh072019 |
Javascript
<script> // Javascript implementation of // the above approach // Function to reverse the words // of the given String without // using strtok(). function reverse(s) { // Create an empty String stack let stc = []; // Create an empty temporary String let temp = ""; // Traversing the entire String for(let i = 0; i < s.length; i++) { if(s[i] == ' ') { // Push the temporary // variable into the stack stc.push(temp); // Assigning temporary // variable as empty temp = ""; } else { temp = temp + s[i]; } } // For the last word // of the String stc.push(temp); while(stc.length != 0) { // Get the words in // reverse order temp = stc[stc.length - 1]; document.write(temp + " "); stc.pop(); } } let s = "I Love To Code"; reverse(s); </script> |
Code To Love I
Time Complexity: O(N)
Another Approach: An approach without using stack is discussed here. This problem can also be solved using stack by following the below steps:
- Create an empty stack.
- Tokenize the input string into words using spaces as separator with the help of strtok()
- Push the words into the stack.
- Pop the words from the stack until the stack is not empty which will be in reverse order.
Below is the implementation of the above approach:
C++
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std;// Function to reverse the words// of the given sentencevoid reverse(char k[]){ // Create an empty character array stack stack<char*> s; char* token = strtok(k, " "); // Push words into the stack while (token != NULL) { s.push(token); token = strtok(NULL, " "); } while (!s.empty()) { // Get the words in reverse order cout << s.top() << " "; s.pop(); }}// Driver codeint main(){ char k[] = "geeks for geeks"; reverse(k); return 0;} |
Java
// Java implementation of the approachimport java.util.Arrays;import java.util.Stack;class GFG { // Function to reverse the words // of the given sentence static void reverse(String k) { // Create an empty character array stack Stack<String> s = new Stack<>(); String[] token = k.split(" "); // Push words into the stack for (int i = 0; i < token.length; i++) { s.push(token[i]); } while (!s.empty()) { // Get the words in reverse order System.out.print(s.peek() + " "); s.pop(); } } // Driver code public static void main(String[] args) { String k = "geeks for geeks"; reverse(k); }}// This code is contributed by Rajput-Ji |
Python3
# Python3 implementation of the approach# Function to reverse the words# of the given sentencedef reverse(k): # Create an empty character array stack s = [] token = k.split() # Push words into the stack for word in token : s.append(word); while (len(s)) : # Get the words in reverse order print(s.pop(), end = " "); # Driver codeif __name__ == "__main__" : k = "geeks for geeks"; reverse(k); # This code is contributed by AnkitRai01 |
C#
// C# implementation of the approachusing System;using System.Collections.Generic;class GFG { // Function to reverse the words // of the given sentence static void reverse(String k) { // Create an empty character array stack Stack<String> s = new Stack<String>(); String[] token = k.Split(' '); // Push words into the stack for (int i = 0; i < token.Length; i++) { s.Push(token[i]); } while (s.Count != 0) { // Get the words in reverse order Console.Write(s.Peek() + " "); s.Pop(); } } // Driver code public static void Main(String[] args) { String k = "geeks for geeks"; reverse(k); }}// This code is contributed by PrinciRaj1992 |
geeks for geeks
Time Complexity: 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. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
In case you wish to attend live classes with industry experts, please refer DSA Live Classes


