Given string str, we need to print the 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 word 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.
Implementation:
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 string void 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 function int main() { Â Â Â Â string str = "Geeks for Geeks" ; Â Â Â Â reverseWords(str); Â Â Â Â return 0; } |
Java
// Java program to reverse individual // words in a given string using STL list import java.io.*; import java.util.*; Â
class GFG { Â
    // reverses individual words of a string     static 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 function     public 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 string Â
Â
def reverseWords(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 Code if __name__ = = "__main__" : Â Â Â Â string = "Geeks for Geeks" Â Â Â Â reverseWords(string) Â
# This code is contributed by # sanjeev2552 |
C#
// C# program to reverse individual // words in a given string using STL list using System; using System.Collections.Generic; Â
class GFG { Â
// reverses individual words // of a string public 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 Code public static void Main( string [] args) { Â Â Â Â string str = "Geeks for Geeks" ; Â Â Â Â reverseWords(str); } } Â
// This code is contributed // by Shrikant13 |
Javascript
// JS program to reverse individual words in a given // string using STL list Â
Â
// reverses individual words of a string function reverseWords(str) { Â Â Â Â let st = []; Â
    // Traverse given string and push all characters     // to stack until we see a space.     for (let i = 0; i < str.length; ++i) {         if (str[i] != ' ' )             st.unshift(str[i]); Â
        // When we see a space, we print contents         // of stack.         else {             while (st.length != 0) {                 process.stdout.write(st[0]);             st.shift();             }             process.stdout.write( ' ' );         }     } Â
    // Since there may not be space after     // last word.     while (st.length != 0) {     process.stdout.write(st[0]);         st.shift();     } } Â
// Driver program to test function let str = "Geeks for Geeks" ; reverseWords(str); Â
// This code is contributed by adityamaharshi21 |
Output
skeeG rof skeeG
Time Complexity: O(n), where n is the length of the string
Auxiliary Space: O(n), where n is the length of the string
Python | Reverse each word in a sentence
Using stringstream in C++ :
Implementation:
C++
#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 code int main() { Â Â Â Â string s = "neveropen is good to learn" ; Â Â Â Â printWords(s); Â Â Â Â return 0; } // This code is contributed by Nikhil Rawat |
Java
import java.io.*; import java.lang.*; import java.util.*; Â
class Main {     public static void printWords(String str)     {         // word variable to store word         String word; Â
        // making a string stream         StringTokenizer iss = new StringTokenizer(str); Â
        // Read and print each word.         while (iss.hasMoreTokens()) {             word = iss.nextToken();             System.out.print(                 new StringBuilder(word).reverse().toString()                 + " " );         }     } Â
    public static void main(String[] args)         throws java.lang.Exception     {         String s = "neveropen is good to learn" ;         printWords(s);     } } Â
// Contributed by rishabmalhdijo |
Python3
def print_words(s):     # word variable to store word     word = "" Â
    # making a string stream     iss = s.split() Â
    # Read and print each word.     for i in iss:         word = i[:: - 1 ]         print (word, end = " " ) Â
Â
# Driver code if __name__ = = '__main__' : Â Â Â Â s = "neveropen is good to learn" Â Â Â Â print_words(s) |
C#
using System; using System.Linq; using System.Collections.Generic; using System.Text; using System.IO; Â
public class GFG {     static void printWords( string str)     {         // word variable to store word         string word; Â
        // making a string stream         using ( var iss = new StringReader(str))         {             string line;             while ((line = iss.ReadLine()) != null ) {                 // Read and print each word.                 foreach ( string w in line.Split( ' ' ))                 {                     word                         = new string (w.Reverse().ToArray());                     Console.Write(word + " " );                 }             }         }     } Â
    // Driver code     static void Main()     {         string s = "neveropen is good to learn" ;         printWords(s);     } } // ksam24000 |
Javascript
function printWords(str) { Â
    // word variable to store word     let word;          // making a string stream     let lines = str.split( "\n" );     for (let i = 0; i < lines.length; i++) {         let words = lines[i].split( " " );                  for (let j = 0; j < words.length; j++) {             word = words[j].split( "" ).reverse().join( "" );             process.stdout.write(word + " " );         }     } } Â
// Driver Code let s = "neveropen is good to learn" ; printWords(s); |
Output
skeeGrofskeeG si doog ot nrael
Time complexity : O(n)
Auxiliary Space : O(n)
Using Java 8 Streams:
Implementation:
C++
#include <bits/stdc++.h> using namespace std; Â
int main() { string str = "Welcome to GFG" ; Â Â Â Â string result = "" ; Â
    // Splitting the string based on space     istringstream ss(str);     vector<string> words;     do {         string word;         ss >> word;         words.push_back(word);     } while (ss); Â
    // Reverse each part and then join     for ( int i = 0; i < words.size() - 1; i++) {         reverse(words[i].begin(), words[i].end());         result += words[i] + ' ' ;     }     reverse(words.back().begin(), words.back().end());     result += words.back(); Â
    cout << result << endl;     return 0; } //This code is contributed by Shivam Tiwari |
Java
import java.util.Arrays; import java.util.stream.Collectors; Â
// This code is contributed by Mayank Sharma public 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); Â
    } Â
} |
Python3
# python code Â
import re Â
def reverseIndividual( str ): Â Â Â Â words = re.findall(r '\b\w+\b' , str ) Â Â Â Â result = " " .join(word[:: - 1 ] for word in words) Â Â Â Â return result Â
str = "Welcome to GFG" print (reverseIndividual( str )) Â
#code by ksam24000 |
C#
using System; using System.Linq; Â
public 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 = string .Join( " " , str.Split( ' ' )             .Select(word => new string (word.Reverse().ToArray()))); Â
        Console.WriteLine(result);     } } |
Javascript
function reverseIndividualWords(str) {     // Split the string based on space     const words = str.split( ' ' ); Â
    // Reverse each word and join them back with space     const reversedWords = words.map(word => word.split( '' ).reverse().join( '' )); Â
    // Join the reversed words to form the final result     const result = reversedWords.join( ' ' ); Â
    return result; } Â
const str = 'Welcome to GFG' ; const reversedStr = reverseIndividualWords(str); console.log(reversedStr); |
Output
emocleW ot GFG
Time complexity : O(n)
Auxiliary Space: O(n)
Way 3: Using StringBuffer Class.
Approach:
- O(n) First, convert the string object into a StringBuffer object.
- By using the reverse method of the StringBuffer class reverse the string.
- Now, store the reverse sequence in a String array.
- Run a loop that will create a new String by using these reverse words
- Finally, return the new string.
Implementation:
C++
#include <algorithm> #include <iostream> #include <sstream> #include <string> Â
std::string makeReverse(std::string str) { Â Â Â Â std::reverse(str.begin(), str.end()); Â Â Â Â std::istringstream iss(str); Â Â Â Â std::string word; Â Â Â Â std::string reverse; Â Â Â Â while (iss >> word) { Â Â Â Â Â Â Â Â reverse = word + " " + reverse; Â Â Â Â } Â Â Â Â return reverse; } Â
int main() { Â Â Â Â std::string str = "Geeks for Geeks" ; Â Â Â Â std::cout << makeReverse(str) << std::endl; Â Â Â Â return 0; } |
Java
/*package whatever //do not write package name here */ Â
import java.io.*; Â
class GFG { Â Â Â Â static String makeReverse(String str) Â Â Â Â { Â Â Â Â Â Â Â Â StringBuffer s = new StringBuffer(str); Â Â Â Â Â Â Â Â str = s.reverse().toString(); Â Â Â Â Â Â Â Â String[] rev = str.split( " " ); Â Â Â Â Â Â Â Â StringBuffer reverse = new StringBuffer(); Â Â Â Â Â Â Â Â for ( int i = rev.length - 1 ; i >= 0 ; i--) { Â Â Â Â Â Â Â Â Â Â Â Â reverse.append(rev[i]).append( " " ); Â Â Â Â Â Â Â Â } Â Â Â Â Â Â Â Â return reverse.toString(); Â Â Â Â } Â Â Â Â public static void main(String[] args) Â Â Â Â { Â Â Â Â Â Â Â Â String str = "Geeks for Geeks" ; Â Â Â Â Â Â Â Â System.out.println(makeReverse(str)); Â Â Â Â } } Â
// This code is contributed by Adarsh Kumar |
Python3
# Function to make the reverse of the string def make_reverse(string: str ) - > str :     # Reversing the string     string = string[:: - 1 ]     # Splitting the string by space     rev = string.split( " " )     # Reversing the list of words     rev = rev[:: - 1 ]     # Joining the words to form a new string     reversed_string = " " .join(rev)     return reversed_string Â
Â
# Driver code if __name__ = = "__main__" : Â Â Â Â string = "Geeks for Geeks" Â Â Â Â print (make_reverse(string)) Â
# This code is contributed by Shivam Tiwari |
C#
using System; Â
class GFG { Â Â Â Â static string MakeReverse( string str) Â Â Â Â { Â Â Â Â Â Â Â Â char [] charArray = str.ToCharArray(); Â Â Â Â Â Â Â Â Array.Reverse(charArray); Â Â Â Â Â Â Â Â str = new string (charArray); Â Â Â Â Â Â Â Â string [] rev = str.Split( ' ' ); Â Â Â Â Â Â Â Â Array.Reverse(rev); Â Â Â Â Â Â Â Â return string .Join( " " , rev); Â Â Â Â } Â
    public static void Main()     {         string str = "Geeks for Geeks" ;         Console.WriteLine(MakeReverse(str));     } } |
Javascript
// Javascript code addition Â
function makeReverse(string) { // Reversing the string string = string.split( "" ).reverse().join( "" ); // Splitting the string by space let rev = string.split( " " ); // Reversing the list of words rev = rev.reverse(); // Joining the words to form a new string let reversedString = rev.join( " " ); return reversedString; } Â
// Driver code let string = "Geeks for Geeks" ; console.log(makeReverse(string)); Â
// The code is contributed by Nidhi goel. |
Output
skeeG rof skeeG
Time complexity : O(n)
Auxiliary Space : O(n)
Way 4 :
Approach: To store the reversed string instead of just printing
Steps:
- Create an empty stack to hold characters from the input string. Create two empty strings: ‘rev’ (for the reversed string) and ‘temp’ (for temporary storage).
- Iterate through each character in the input string.
- If the current character is a letter (an alphabet character) Add it to the ‘temp’ string to form a word .
- If the current character is a space Append a space to the ‘rev’ string to separate words. Append the content of ‘temp’ (a word) to ‘rev’. Clear ‘temp’ to prepare for the next word.
- After processing all characters. If ‘temp’ is not empty then add the content of ‘temp’ to the beginning of the ‘rev’ string.
- Finally, return the ‘rev’ string.
C++
#include <iostream> #include <stack> Â
class Reverse { public :     // function to reverse the individual words     std::string reverse(std::string str) {         // create a stack to access the string from end         std::stack< char > s; Â
        // push all the characters of the stack         for ( int i = 0; i < str.length(); i++)             s.push(str[i]); Â
        // rev string to store the required output         std::string rev = "" ;         std::string temp = "" ; Â
        // till the stack becomes empty         while (!s.empty()) {             // if top of the stack is a letter,             // then append it to temp;             if ( isalpha (s.top()))                 temp += s.top();             // if it is a space, then 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.empty())             rev = temp + rev; Â
        // return the output string         return rev;     } }; Â
int main() { Â Â Â Â std::string str = "Geeks for Geeks" ; Â
    Reverse obj;     std::cout << obj.reverse(str) << std::endl;          return 0; } Â
// Siddhesh |
Java
// Java program to reverse the individual words Â
import 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));     } } |
Python3
class Reverse: Â
    # function to reverse the individual words     def reverse( self , string):         # create a stack to access the string from end         stack = [] Â
        # push all the characters of the string onto the stack         for i in range ( len (string)):             stack.append(string[i]) Â
        # rev string to store the required output         rev = ""         temp = "" Â
        # till the stack becomes empty         while len (stack) > 0 :             # if top of the stack is a letter, then append it to temp             if stack[ - 1 ].isalpha():                 temp = temp + stack.pop()             # if it is a space, append space to rev and also temp to rev             else :                 rev = " " + temp + rev                 # make the temp empty                 temp = ""                 stack.pop() Â
        # if temp is not empty, add temp to rev at the front         if temp ! = "":             rev = temp + rev Â
        # return the output string         return rev Â
Â
# main driver function if __name__ = = '__main__' : Â Â Â Â str = "Geeks for Geeks" Â
    obj = Reverse()     print (obj.reverse( str )) |
C#
using System; using System.Collections.Generic; Â
class Reverse {     // Renamed the method to ReverseWords     public string ReverseWords( string str)     {         // create a stack to access the string from end         Stack< char > stack = new Stack< char >(); Â
        // push all the characters onto the stack         for ( int i = 0; i < str.Length; i++)         {             stack.Push(str[i]);         } Â
        // rev string to store the required output         string rev = "" ;         string temp = "" ; Â
        // until the stack becomes empty         while (stack.Count > 0)         {             // if the top of the stack is a letter,             // then append it to temp;             if ( char .IsLetter(stack.Peek()))             {                 temp += stack.Pop();             }             // if it is a space, then append space to rev             // and also temp to rev             else             {                 rev = " " + temp + rev;                 // make the temp empty                 temp = "" ;                 stack.Pop();             }         }         // if temp is not empty, add temp to rev at the front         if (! string .IsNullOrEmpty(temp))         {             rev = temp + rev;         } Â
        // return the output string         return rev;     } } Â
class Program { Â Â Â Â static void Main() Â Â Â Â { Â Â Â Â Â Â Â Â string str = "Geeks for Geeks" ; Â
        Reverse obj = new Reverse();         Console.WriteLine(obj.ReverseWords(str)); Â
        // Pause execution to see the result         Console.ReadLine();     } } // contributed Siddhesh |
Javascript
class Reverse {     // function to reverse the individual words     reverse(str) {         // create an array (stack) to access the string from end         const stack = []; Â
        // push all the characters onto the stack         for (let i = 0; i < str.length; i++) {             stack.push(str.charAt(i));         } Â
        // rev string to store the required output         let rev = '' ;         let temp = '' ; Â
        // until the stack becomes empty         while (stack.length > 0) {             // if top of the stack is a letter,             // then append it to temp;             if (/[a-zA-Z]/.test(stack[stack.length - 1])) {                 temp += stack.pop();             }             // if it is a space, then append space to rev             // and also temp to rev             else {                 rev = ' ' + temp + rev;                 // make the temp empty                 temp = '' ;                 stack.pop();             }         }         // if temp is not empty, add temp to rev at the front         if (temp !== '' ) {             rev = temp + rev;         } Â
        // return the output string         return rev;     } } Â
// Testing the Reverse class const str = 'Geeks for Geeks' ; const obj = new Reverse(); console.log(obj.reverse(str)); |
skeeG rof skeeG
Time Complexity : O(N)
Auxiliary Space : O(N) for using stack .
Using Split and iterator in Python
Implementation:
Python3
def rev_sentence(sentence): Â
    # first split the string into words     words = sentence.split( ' ' )     reverse_sentence = ""     for i in words:         reverse_sentence + = i[:: - 1 ] + ' '     # then reverse the split string list and join using space Â
    # finally return the joined string     return reverse_sentence Â
Â
if __name__ = = "__main__" : Â Â Â Â input = 'neveropen quiz practice code' Â Â Â Â print (rev_sentence( input )) |
Output
skeeg ziuq ecitcarp edoc
Time Complexity: O(n)
Auxiliary Space:: O(n)
Method: Using join and split functions
Implementation:
Python3
# Python code to reverse words Â
s = " Geeks for Geeks" l = [] # splitting the string s = s.split() for i in s:     # reversing each word     l.append(i[:: - 1 ]) # printing string using join Â
# function after reversing the # words Â
Â
print ( " " .join(l)) |
Output
skeeG rof skeeG
Time Complexity: O(n)
Auxiliary Space: O(n)
Solve DSA problems on GfG Practice.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!