Reverse individual words
Given a string str, we need to print reverse of individual words.
Examples:
Input : Hello World Output : olleH dlroW Input : Geeks for Geeks Output : skeeG rof skeeG
Method 1 (Simple): Generate all words separated by space. One by one reverse words and print them separated by space.
Method 2 (Space Efficient): We use a stack to push all words before space. As soon as we encounter a space, we empty the stack.
C++
// C++ program to reverse individual words in a given// string using STL list#include <bits/stdc++.h>using namespace std;// reverses individual words of a stringvoid reverseWords(string str){ stack<char> st; // Traverse given string and push all characters // to stack until we see a space. for (int i = 0; i < str.length(); ++i) { if (str[i] != ' ') st.push(str[i]); // When we see a space, we print contents // of stack. else { while (st.empty() == false) { cout << st.top(); st.pop(); } cout << " "; } } // Since there may not be space after // last word. while (st.empty() == false) { cout << st.top(); st.pop(); }}// Driver program to test functionint main(){ string str = "Geeks for Geeks"; reverseWords(str); return 0;} |
Java
// Java program to reverse individual// words in a given string using STL listimport java.io.*;import java.util.*;class GFG {// reverses individual words of a stringstatic void reverseWords(String str){ Stack<Character> st=new Stack<Character>(); // Traverse given string and push all // characters to stack until we see a space. for (int i = 0; i < str.length(); ++i) { if (str.charAt(i) != ' ') st.push(str.charAt(i)); // When we see a space, we print // contents of stack. else { while (st.empty() == false) { System.out.print(st.pop()); } System.out.print(" "); } } // Since there may not be space after // last word. while (st.empty() == false) { System.out.print(st.pop()); }}// Driver program to test above functionpublic static void main(String[] args){ String str = "Geeks for Geeks"; reverseWords(str); }} |
Python3
# Python3 program to reverse individual words# in a given string using STL list# reverses individual words of a stringdef reverserWords(string): st = list() # Traverse given string and push all characters # to stack until we see a space. for i in range(len(string)): if string[i] != " ": st.append(string[i]) # When we see a space, we print # contents of stack. else: while len(st) > 0: print(st[-1], end= "") st.pop() print(end = " ") # Since there may not be space after # last word. while len(st) > 0: print(st[-1], end = "") st.pop()# Driver Codeif __name__ == "__main__": string = "Geeks for Geeks" reverserWords(string)# This code is contributed by# sanjeev2552 |
C#
// C# program to reverse individual// words in a given string using STL listusing System;using System.Collections.Generic;class GFG{// reverses individual words// of a stringpublic static void reverseWords(string str){ Stack<char> st = new Stack<char>(); // Traverse given string and push // all characters to stack until // we see a space. for (int i = 0; i < str.Length; ++i) { if (str[i] != ' ') { st.Push(str[i]); } // When we see a space, we // print contents of stack. else { while (st.Count > 0) { Console.Write(st.Pop()); } Console.Write(" "); } } // Since there may not be // space after last word. while (st.Count > 0) { Console.Write(st.Pop()); }}// Driver Codepublic static void Main(string[] args){ string str = "Geeks for Geeks"; reverseWords(str);}}// This code is contributed// by Shrikant13 |
Output:
skeeG rof skeeG
Python | Reverse each word in a sentence
Using stringstream in C++ :
CPP
#include<bits/stdc++.h>using namespace std; void printWords(string str){ // word variable to store word string word; // making a string stream stringstream iss(str); // Read and print each word. while (iss >> word){ reverse(word.begin(),word.end()); cout<<word<<" "; }} // Driver codeint main(){ string s = "GeeksforGeeks is good to learn"; printWords(s); return 0;}// This code is contributed by Nikhil Rawat |
Output:
skeeGrofskeeG si doog ot nrael
Time complexity : O(n)
Space complexity : O(n)
Using Java 8 Streams
Java
import java.util.Arrays;import java.util.stream.Collectors;// This code is contributed by Mayank Sharmapublic class reverseIndividual { public static void main(String[] args) { String str = "Welcome to GFG"; // Splitting the string based on space and reverse each part // and then join String result = Arrays.asList(str.split(" ")) .stream() .map(s -> new StringBuilder(s).reverse()) .collect(Collectors.joining(" ")); System.out.println(result); }} |
Output:
emocleW ot GFG
Alternate Approach: To store the reversed string instead of just printing
Steps:
- Create a stack and push all the characters of the given input string.
- Create ‘rev’ and ‘temp’ strings
- Do the following steps till the stack becomes empty.
- If the peek( ) of the stack is a character, append it to temp
- If the peek( ) of the stack is a space, then append space to rev and also temp to rev
- Finally, if the temp is not empty, append the temp to rev in the front
- Return the reversed string
Implementation:
Java
//java program to reverse the individual wordsimport java.util.Stack;public class Reverse { //function to reverse the individual words String reverse(String str) { //create a stack to access the string from end Stack<Character> s = new Stack<>(); //push all the characters of the stack for(int i = 0; i < str.length();i++) s.push(str.charAt(i)); //rev string to store the required output String rev = ""; String temp = ""; //till the stack becomes empty while(!s.isEmpty()) { //if top of the stack is a letter, //then append it to temp; if(Character.isLetter(s.peek())) temp = temp + s.pop(); //if it is a space, the append space to rev //and also temp to rev else { rev = " " + temp +rev; //make the temp empty temp = ""; s.pop(); } } //if temp is not empty, add temp to rev at the front if(temp != "") rev = temp + rev; //return the output string return rev; } public static void main(String[] args) { String str = "Geeks for Geeks"; Reverse obj = new Reverse(); System.out.println(obj.reverse(str)); }}//This method is contributed by Likhita AVL |
skeeG rof skeeG
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 experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.



