Reverse individual words
Last Updated :
13 Apr, 2024
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
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
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:
- 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
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:
- 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));
}
}
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))
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)
Please Login to comment...