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++

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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);
  }
}

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to reverse individual words 
# in a given string using STL list
  
# reverses individual words of a string
def 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 Code
if __name__ == "__main__":
    string = "Geeks for Geeks"
    reverserWords(string)
  
# This code is contributed by
# sanjeev2552

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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

chevron_right



Output:

skeeG rof skeeG

Python | Reverse each word in a sentence

Using stringstream in C++ :

filter_none

edit
close

play_arrow

link
brightness_4
code

#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 = "GeeksforGeeks is good to learn";
    printWords(s);
    return 0;
}
// This code is contributed by Nikhil Rawat

chevron_right


Time complexity : O(n)
Space complexity : O(n)



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.



Improved By : shrikanth13, sanjeev2552