The Wayback Machine - https://web.archive.org/web/20240927182417/https://www.geeksforgeeks.org/reverse-individual-words/
Open In App

Reverse individual words

Last Updated : 13 Apr, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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();
            }
            //Add space after word is reversed.
            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 = "GeeksforGeeks 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 = "GeeksforGeeks is good to learn";
        printWords(s);
    }
}

// Contributed by rishabmalhdijo

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 = "GeeksforGeeks 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 = "GeeksforGeeks is good to learn";
printWords(s);

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 = "GeeksforGeeks is good to learn"
    print_words(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);

    }

}

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

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

Output

emocleW ot GFG

Time complexity : O(n)

Auxiliary Space: O(n)


Way 3: Using StringBuffer Class.

Approach:

  1. O(n) First, convert the string object into a StringBuffer object.
  2. By using the reverse method of the StringBuffer class reverse the string.
  3. Now, store the reverse sequence in a String array.
  4. Run a loop that will create a new String by using these reverse words
  5. 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

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.

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

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:

  1. 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).
  2. Iterate through each character in the input string.
  3. If the current character is a letter (an alphabet character) Add it to the ‘temp’ string to form a word .
  4. 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.
  5. After processing all characters. If ‘temp’ is not empty then add the content of ‘temp’ to the beginning of the ‘rev’ string.
  6. 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));
    }
}

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

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


Output
skeeG rof skeeG





















Time Complexity : O(N)

Auxiliary Space : O(N) for using stack .

Way 5 : Using Split and iterator

Implementation:

C++

#include <algorithm>
#include <iostream>
#include <sstream>

class ReverseSentence {
public:
    // Function to reverse each word in a sentence
    static std::string
    revSentence(const std::string& sentence)
    {
        // Split the string into words
        std::istringstream iss(sentence);
        std::string word;
        std::ostringstream reverseSentence;

        while (iss >> word) {
            // Reverse each word and append to the result
            std::reverse(word.begin(), word.end());
            reverseSentence << word << " ";
        }

        // Remove the trailing space and return the result
        return reverseSentence.str().substr(
            0, reverseSentence.str().size() - 1);
    }
};

int main()
{
    std::string input = "geeks quiz practice code";
    std::cout << ReverseSentence::revSentence(input)
              << std::endl;
    return 0;
}

Java

public class ReverseSentence {
    public static String revSentence(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 quiz practice code";
        System.out.println(revSentence(input));
    }
}
// Contributed by siddhesh

C#

using System;
using System.Text;

public class ReverseSentence {
    // Function to reverse each word in a sentence
    public static string RevSentence(string sentence)
    {
        // Split the string into words
        string[] words = sentence.Split(' ');
        StringBuilder reverseSentence = new StringBuilder();

        // Reverse each word and append to the result
        foreach(string word in words)
        {
            char[] charArray = word.ToCharArray();
            Array.Reverse(charArray);
            reverseSentence.Append(new string(charArray))
                .Append(" ");
        }

        // Remove the trailing space and return the result
        return reverseSentence.ToString().Trim();
    }

    public static void Main()
    {
        string input = "geeks quiz practice code";
        Console.WriteLine(RevSentence(input));
    }
}

Javascript

class ReverseSentence {
    // Function to reverse each word in a sentence
    static revSentence(sentence) {
        // Split the string into words
        const words = sentence.split(' ');

        // Reverse each word and join them back
        const reversedWords = words.map(word => word.split('').reverse().join(''));

        // Join the reversed words into a sentence
        const reversedSentence = reversedWords.join(' ');

        return reversedSentence;
    }
}

const input = "geeks quiz practice code";
console.log(ReverseSentence.revSentence(input));

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 = 'geeks 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:

C++

#include <iostream>
#include <vector>
#include <sstream> // Required for std::stringstream

using namespace std;

// Function to reverse words in a string
string reverseWords(string s) {
    stringstream ss(s); // Create a string stream from input string
    string word;
    vector<string> words;

    // Splitting the string into words
    while (ss >> word) {
        // Reversing each word
        string reversedWord = "";
        for (int i = word.length() - 1; i >= 0; i--) {
            reversedWord += word[i];
        }
        // Storing reversed word
        words.push_back(reversedWord);
    }

    // Joining the reversed words back into a string
    string result = "";
    for (int i = 0; i < words.size(); i++) {
        result += words[i];
        if (i != words.size() - 1) {
            result += " ";
        }
    }

    return result;
}

int main() {
    string s = "Geeks for Geeks";

    // Reversing words in the string
    string reversedString = reverseWords(s);

    // Printing the reversed string
    cout << reversedString << endl;

    return 0;
}
//this code is contributed by Adarsh.

Java

import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

public class ReverseWords {
    // Function to reverse words in a string
    static String reverseWords(String s) {
        StringTokenizer tokenizer = new StringTokenizer(s);
        List<String> words = new ArrayList<>();

        // Splitting the string into words
        while (tokenizer.hasMoreTokens()) {
            String word = tokenizer.nextToken();
            // Reversing each word
            StringBuilder reversedWord = new StringBuilder();
            for (int i = word.length() - 1; i >= 0; i--) {
                reversedWord.append(word.charAt(i));
            }
            // Storing reversed word
            words.add(reversedWord.toString());
        }

        // Joining the reversed words back into a string
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < words.size(); i++) {
            result.append(words.get(i));
            if (i != words.size() - 1) {
                result.append(" ");
            }
        }

        return result.toString();
    }

    public static void main(String[] args) {
        String s = "Geeks for Geeks";

        // Reversing words in the string
        String reversedString = reverseWords(s);

        // Printing the reversed string
        System.out.println(reversedString);
    }
}

C#

using System;
using System.Collections.Generic;
using System.Text;

class Program {
    // Function to reverse words in a string
    static string ReverseWords(string s)
    {
        string[] words
            = s.Split(' '); // Split the string into words
        StringBuilder result = new StringBuilder();

        foreach(string word in words)
        {
            // Reverse each word and append to result
            char[] charArray = word.ToCharArray();
            Array.Reverse(charArray);
            result.Append(new string(charArray));
            result.Append(" ");
        }

        // Remove trailing space and return the result
        return result.ToString().Trim();
    }

    static void Main(string[] args)
    {
        string s = "Geeks for Geeks";

        // Reversing words in the string
        string reversedString = ReverseWords(s);

        // Printing the reversed string
        Console.WriteLine(reversedString);
    }
}

Javascript

let s = "Geeks for Geeks";
let words = s.split(' ');

for (let i = 0; i < words.length; i++) {
    // Reversing each word
    words[i] = words[i].split('').reverse().join('');
}

// Joining the words back into a string
let reversedString = words.join(' ');

console.log(reversedString);

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)



Previous Article
Next Article

Similar Reads

Find all words from String present after given N words
Given a string S and a list lis[] of N number of words, the task is to find every possible (N+1)th word from string S such that the 'second' word comes immediately after the 'first' word, the 'third' word comes immediately after the 'second' word, the 'fourth' word comes immediately after the 'third' word and so on. Examples: Input: S = “Siddhesh i
11 min read
Count words that appear exactly two times in an array of words
Given an array of n words. Some words are repeated twice, we need to count such words. Examples: Input : s[] = {"hate", "love", "peace", "love", "peace", "hate", "love", "peace", "love", "peace"}; Output : 1 There is only one word "hate" that appears twice Input : s[] = {"Om", "Om", "Shankar", "Tripathi", "Tom", "Jerry", "Jerry"}; Output : 2 There
6 min read
Sum of heights of all individual nodes in a binary tree
Given a binary tree, find the sum of heights of all individual nodes in the tree. Example: For this tree: 1). Height of Node 1 - 3 2). Height of Node 2 - 2 3). Height of Node 3 - 1 4). Height of Node 4 - 1 5). Height of Node 5 - 1 Adding all of them = 8 Prerequisites:- Height of binary tree Simple Solution: We get the height of all individual nodes
11 min read
Partition the array in K segments such that bitwise AND of individual segment sum is maximized
Given an array of size N and an integer K. The task is to partition the array in K segments such that bitwise AND of individual segment sum is maximized. Find the maximum value of bitwise AND which can be obtained. Examples: Input : a[] = { 2, 5, 6, 9, 1, 3, 10, 12 }, K = 3 Output : 8 Explanation : Maximum bitwise AND can be obtained by making cut
12 min read
Find the ratio of number of elements in two Arrays from their individual and combined average
Given the average of elements in two arrays as 'a' and 'b' respectively, and their combined average as 'c', the task is to find the ratio of the number of elements in two array.Examples: Input: a = 2, b = 8, c = 5 Output: 1:1 Input: a = 4, b = 10, c = 6 Output: 2:1 Approach: Let the number of elements in two arrays are respectively x and y.So sum o
4 min read
Check if alternate path exists from U to V with smaller individual weight in a given Graph
Given a directed weighted graph with N vertices and M edges and an edge (U, V). The task is to find whether there is an alternate path present from U to V with individual weight of edges in alternate path less than the weight of direct path. If present print Yes else print No. Examples For the given directed graph: Input: N = 7, M = 10, U = 3, V =
10 min read
Search in matrix where only individual columns are sorted
Given a semi-sorted (every column is individually sorted) matrix mat[n][m] and an element 'x'. Find the position of x in the matrix if it is present, else print -1. Note that there is no ordering among row elements. Examples: Input : mat[][] = { {10, 1, 3}, {50, 2, 5}, {90, 34, 43} } x = 34Output : Found at (2, 1)Input : mat[][] = { {21, 35, 80, 4}
6 min read
Search in matrix where only individual rows are sorted
Given a semi-sorted (every row is individually sorted) matrix mat[n][m] and an element 'x'. Find the position of x in the matrix if it is present, else print -1. Note that there is no ordering among column elements. Examples: Input : mat[][] = { {10, 50, 90}, {1, 2, 5}, {30, 34, 43} } x = 34Output : Found at (2, 1)Input : mat[][] = { {21, 25, 29, 2
6 min read
Reverse Words in a Given String in Python
We are given a string and we need to reverse words of a given string Examples: Input : str =" geeks quiz practice code" Output : str = code practice quiz geeks Input : str = "my name is laxmi" output : str= laxmi is name my Reverse the words in the given string program C/C++ Code # Python code # To reverse words in a given string # input string str
6 min read
Reverse String according to the number of words
Given a string containing a number of words. If the count of words in string is even then reverse its even position's words else reverse its odd position, push reversed words at the starting of a new string and append the remaining words as it is in order. Examples: Input: Ashish Yadav Abhishek Rajput Sunil Pundir Output: ridnuP tupjaR vadaY Ashish
6 min read
Reverse the Words of a String using Stack
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 IInput: 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
8 min read
Reverse words in a given String in Java
Let's see an approach to reverse words of a given String in Java without using any of the String library function Examples: Input : "Welcome to geeksforgeeks" Output : "geeksforgeeks to Welcome" Input : "I love Java Programming" Output :"Programming Java love I" Prerequisite: Regular Expression in Java Java Code // Java Program to reverse a String
3 min read
Print words of a string in reverse order
Let there be a string say "I AM A GEEK". So, the output should be "GEEK A AM I" . This can done in many ways. One of the solutions is given in Reverse words in a string . Examples: Input : I AM A GEEK Output : GEEK A AM I Input : GfG IS THE BEST Output : BEST THE IS GfG This can be done in more simpler way by using the property of the "%s format sp
10 min read
Javascript Program To Reverse Words In A Given String
Example: Let the input string be "i like this program very much". The function should change the string to "much very program this like i" Examples:  Input: s = "geeks quiz practice code" Output: s = "code practice quiz geeks" Input: s = "getting good at coding needs a lot of practice" Output: s = "practice of lot a needs coding at good getting" Al
4 min read
Reverse words in a string
Given a string str, the task is to reverse the order of the words in the given string. Note that str may contain leading or trailing dots(.) or multiple trailing dots(.) between two words. The returned string should only have a single dot(.) separating the words. Examples: Input: str = "i.like.this.program.very.much" Output: str = "much.very.progra
12 min read
Count of unique pairs (i, j) in an array such that sum of A[i] and reverse of A[j] is equal to sum of reverse of A[i] and A[j]
Given an array arr[] consisting of N positive integers, the task is to find the count of unique pairs (i, j) such that the sum of arr[i] and the reverse(arr[j]) is the same as the sum of reverse(arr[i]) and arr[j]. Examples: Input: arr[] = {2, 15, 11, 7}Output: 3Explanation:The pairs are (0, 2), (0, 3) and (2, 3). (0, 2): arr[0] + reverse(arr[2]) (
7 min read
Remove all the palindromic words from the given sentence
Given a sentence str. The problem is to remove all the palindromic words from the given sentence.Examples: Input : str = "Text contains malayalam and level words" Output : Text contains and words Input : str = "abc bcd" Output : abc bcd Approach: One by one extract all the words. Check if the current word is not a palindrome then add it to the fina
12 min read
Possible Words using given characters in Python
Given a dictionary and a character array, print all valid words that are possible using characters from the array. Note: Repetitions of characters is not allowed. Examples: Input : Dict = ["go","bat","me","eat","goal","boy", "run"] arr = ['e','o','b', 'a','m','g', 'l'] Output : go, me, goal. This problem has existing solution please refer Print all
5 min read
Regex in Python to put spaces between words starting with capital letters
Given an array of characters, which is basically a sentence. However, there is no space between different words and the first letter of every word is in uppercase. You need to print this sentence after the following amendments: Put a single space between these words. Convert the uppercase letters to lowercase Examples: Input : BruceWayneIsBatmanOut
2 min read
Sort the words in lexicographical order in Python
Given a strings, we need to sort the words in lexicographical order (dictionary order). Examples : Input : "hello python program how are you" Output : are hello how program python you Input : "Coders loves the algorithms" Output : Coders algorithms loves the Note: The words which have first letter is capital letter they will print according alphabe
2 min read
Print number of words, vowels and frequency of each character
Given a string str with uppercase, lowercase and special characters. The input string is to end with either a space or a dot. The problem is to calculate the number of words, vowels and frequency of each character of the string in a separate line. Example : Input : How Good GOD Is. Output : Number of words = 4 Number of vowels = 5 Number of upper c
8 min read
Find the size of largest subset of anagram words
Given an array of n string containing lowercase letters. Find the size of largest subset of string which are anagram of each others. An anagram of a string is another string that contains same characters, only the order of characters can be different. For example, “abcd” and “dabc” are anagram of each other. Input: ant magenta magnate tan gnamate O
9 min read
Sorting array of strings (or words) using Trie | Set-2 (Handling Duplicates)
Given an array of strings, print them in alphabetical (dictionary) order. If there are duplicates in input array, we need to print all the occurrences.Examples: Input : arr[] = { "abc", "xyz", "abcd", "bcd", "abc" } Output : abc abc abcd bcd xyz Input : arr[] = { "geeks", "for", "geeks", "a", "portal", "to", "learn" } Output : a for geeks geeks lea
9 min read
Find the starting indices of the substrings in string (S) which is made by concatenating all words from a list(L)
You are given a string S, and a list of words L i.e array/vector of strings (Words in list L are all of the same length). Find the starting indices of the substrings in string S, which contains all the words present in list L. The order of words of list L appearing inside string S does not matter i.e if string S is "barfooapplefoobar" and list of w
10 min read
Python | Sort words of sentence in ascending order
Given a sentence, sort it alphabetically in ascending order. Examples: Input : to learn programming refer geeksforgeeksOutput : geeksforgeeks learn programming refer to Input : geeks for geeksOutput : for geeks geeks Approach 1 : We will use the built-in library function to sort the words of the sentence in ascending order. Prerequisites: split() s
2 min read
Dyck Words of given length
Given an integer n, the task is to count Dyck words possible of length n. A DYCK word is a word containing only characters 'X' and 'Y' such that in every prefix of the word frequency('X') ? frequency('Y')Examples: Input: n = 2 Output: 2 "XY" and "XX" are the only possible DYCK words of length 2.Input: n = 5 Output: 42 Approach: Geometrical Interpre
5 min read
Count palindrome words in a sentence
Given a string str and the task is to count palindrome words present in the string str. Examples: Input : Madam Arora teaches malayalam Output : 3 The string contains three palindrome words (i.e., Madam, Arora, malayalam) so the count is three. Input : Nitin speaks malayalam Output : 2 The string contains two palindrome words (i.e., Nitin, malayala
5 min read
Print all funny words in a string
We are given a sentence. Our task is to print all funny words/strings in that sentence. What is a funny word ? Reverse the given string. Iterate through each character of that string, compare the absolute difference in the ASCII values of the characters at positions 0 and 1, 1 and 2, 2 and 3 and so on to the end. If the list of absolute differences
5 min read
Lex Program to count number of words
Lex is a computer program that generates lexical analyzers and was written by Mike Lesk and Eric Schmidt. Lex reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in the C programming language. Prerequisite: Flex (Fast lexical Analyzer Generator) Example: Input: Hello everyone Output: 2 Input: This is
1 min read
Find alphabetical order such that words can be considered sorted
Given an array of words, find any alphabetical order in the English alphabet such that the given words can be considered sorted (increasing), if there exists such an order, otherwise output impossible. Examples: Input : words[] = {"zy", "ab"} Output : zabcdefghijklmnopqrstuvwxy Basically we need to make sure that 'z' comes before 'a'. Input : words
15 min read