Open In App

Reverse individual words

Last Updated : 17 Mar, 2025
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

Given string str, we need to print the reverse of individual words.

Examples:

Input: Hello World
Output: olleH dlroW
Explanation: Each word in "Hello World" is reversed individually, preserving the original order, resulting in "olleH dlroW".

Input: Geeks for Geeks
Output: skeeG rof skeeG

[Expected Approach] Stack-Based Word Reversal - O(n) Time and O(n) Space

We use a stack to store words character by character until we encounter a space. When a space is found, we pop and print the characters from the stack, effectively reversing the word. This process continues for all words in the string

C++
#include <bits/stdc++.h>
using namespace std;


string reverseWords(string str) {
    stack<char> st;
    string result = "";

    for (int i = 0; i < str.length(); ++i) {
        if (str[i] != ' ') {
            st.push(str[i]);
        } else {
            while (!st.empty()) {
                result += st.top();
                st.pop();
            }
            result += " "; // Add space after the word
        }
    }

    // Reverse the last word (since it may not end with a space)
    while (!st.empty()) {
        result += st.top();
        st.pop();
    }

    return result;
}

// Driver program to test function
int main() {
    string str = "Geeks for Geeks";
    string reversedString = reverseWords(str);
    cout << reversedString << endl;
    return 0;
}
Java
import java.util.Stack;

class GfG {
    
    static String reverseWords(String str) {
        Stack<Character> st = new Stack<>();
        StringBuilder result = new StringBuilder();

        for (int i = 0; i < str.length(); ++i) {
            if (str.charAt(i) != ' ')
                st.push(str.charAt(i));
            else {
                while (!st.isEmpty()) {
                    result.append(st.pop());
                }
                result.append(" ");
            }
        }

        // Reverse the last word (if there's no space after it)
        while (!st.isEmpty()) {
            result.append(st.pop());
        }

        return result.toString();
    }

    // Driver code
    public static void main(String[] args) {
        String str = "Geeks for Geeks";
        String reversed = reverseWords(str);
        System.out.println(reversed);
    }
}
Python
def reverseWords(string):
    st = []
    result = ""

    for i in range(len(string)):
        if string[i] != " ":
            st.append(string[i])
        else:
            while st:
                result += st.pop()
            result += " "

    # Reverse the last word (if any)
    while st:
        result += st.pop()

    return result


# Driver Code
if __name__ == "__main__":
    string = "Geeks for Geeks"
    print(reverseWords(string))  
C#
using System;
using System.Collections.Generic;

class GfG {
    static string ReverseWords(string str)
    {
        Stack<char> st = new Stack<char>();
        string result = "";

        for (int i = 0; i < str.Length; ++i) {
            if (str[i] != ' ') {
                st.Push(str[i]);
            }
            else {
                while (st.Count > 0) {
                    result += st.Pop();
                }
                result += " "; 
            }
        }

        // Reverse the last word (since there may not be
        // space at the end)
        while (st.Count > 0) {
            result += st.Pop();
        }

        return result;
    }

    // Driver Code
    public static void Main(string[] args)
    {
        string str = "Geeks for Geeks";
        string reversed = ReverseWords(str);
        Console.WriteLine(reversed);
    }
}
JavaScript
function reverseWords(str)
{
    let st = [];
    let result = "";

    for (let i = 0; i < str.length; ++i) {
        if (str[i] !== " ")
            // Push character to stack
            st.unshift(str[i]);
        else {
            while (st.length !== 0) {
                // Pop from stack and append
                result += st.shift();
            }
            // Add space after word is reversed
            result += " ";
        }
    }

    // Reverse the last word
    while (st.length !== 0) {
        result += st.shift();
    }

    return result;
}

// Test the function
let str = "Geeks for Geeks";
// Output: "skeeG rof skeeG"
console.log(reverseWords(str));

Output
skeeG rof skeeG

[Alternate Approach] Using Inbulit Functions - O(n) Time and O(n) Space

To reverse individual words in a string, we can use built-in functions like stringstream in C++, StringBuilder in Java, split in Python and other languages. After splitting the string into words, we iterate over each word and reverse it using the reverse function.

C++
#include <bits/stdc++.h>
using namespace std;

string reverseWords(string str)
{
    // word variable to store word
    string word;

    // making a string stream
    stringstream iss(str);

    // Read and print each word.
    string s1 = "";
    while (iss >> word) {
        reverse(word.begin(), word.end());
        s1 += word;
        s1 += " ";
    }
    return s1;
}

// Driver code
int main()
{
    string s = "Geeks for Geeks";
    string s1 = reverseWords(s);
    cout<<s1;
    return 0;
}
Java
public class GfG {
    public static String reverseWords(String sentence)
    {
        // Split the string into words
        String[] words = sentence.split(" ");
        StringBuilder reverseSentence = new StringBuilder();

        // Reverse each word and append to the result
        for (String word : words) {
            reverseSentence
                .append(new StringBuilder(word)
                            .reverse()
                            .toString())
                .append(" ");
        }

        // Remove the trailing space and return the result
        return reverseSentence.toString().trim();
    }

    public static void main(String[] args)
    {
        String input = "Geeks for Geeks";
        System.out.println(reverseWords(input));
    }
}
Python
# Function to make the reverse of the string
def reverseWords(string: 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(reverseWords(string))
C#
using System;
using System.Linq;

public class GfG {
    static string reverseWords(string s)
    {
        return string.Join(
            " ", s.Split(' ').Select(
                     word => new string(
                                word.Reverse().ToArray())));
    }
    public static void Main(string[] args)
    {
        string str = "Geeks for Geeks";

        // Splitting the string based on space and reverse
        // each part and then join
        string result = reverseWords(str);

        Console.WriteLine(result);
    }
}
JavaScript
function reverseWords(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 = "Geeks for Geeks";
const reversedStr = reverseWords(str);
console.log(reversedStr);

Output
skeeG rof skeeG 

Related Article:



Next Article

Similar Reads