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++
#include <bits/stdc++.h>
using namespace std;
void reverseWords(string str)
{
stack< char > st;
for ( int i = 0; i < str.length(); ++i) {
if (str[i] != ' ' )
st.push(str[i]);
else {
while (st.empty() == false ) {
cout << st.top();
st.pop();
}
cout << " " ;
}
}
while (st.empty() == false ) {
cout << st.top();
st.pop();
}
}
int main()
{
string str = "Geeks for Geeks" ;
reverseWords(str);
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class GFG {
static void reverseWords(String str)
{
Stack<Character> st = new Stack<Character>();
for ( int i = 0 ; i < str.length(); ++i) {
if (str.charAt(i) != ' ' )
st.push(str.charAt(i));
else {
while (st.empty() == false ) {
System.out.print(st.pop());
}
System.out.print( " " );
}
}
while (st.empty() == false ) {
System.out.print(st.pop());
}
}
public static void main(String[] args)
{
String str = "Geeks for Geeks" ;
reverseWords(str);
}
}
|
Python3
def reverseWords(string):
st = list ()
for i in range ( len (string)):
if string[i] ! = " " :
st.append(string[i])
else :
while len (st) > 0 :
print (st[ - 1 ], end = "")
st.pop()
print (end = " " )
while len (st) > 0 :
print (st[ - 1 ], end = "")
st.pop()
if __name__ = = "__main__" :
string = "Geeks for Geeks"
reverseWords(string)
|
C#
using System;
using System.Collections.Generic;
class GFG
{
public static void reverseWords( string str)
{
Stack< char > st = new Stack< char >();
for ( int i = 0; i < str.Length; ++i)
{
if (str[i] != ' ' )
{
st.Push(str[i]);
}
else
{
while (st.Count > 0)
{
Console.Write(st.Pop());
}
Console.Write( " " );
}
}
while (st.Count > 0)
{
Console.Write(st.Pop());
}
}
public static void Main( string [] args)
{
string str = "Geeks for Geeks" ;
reverseWords(str);
}
}
|
Javascript
function reverseWords(str) {
let st = [];
for (let i = 0; i < str.length; ++i) {
if (str[i] != ' ' )
st.unshift(str[i]);
else {
while (st.length != 0) {
process.stdout.write(st[0]);
st.shift();
}
process.stdout.write( ' ' );
}
}
while (st.length != 0) {
process.stdout.write(st[0]);
st.shift();
}
}
let str = "Geeks for Geeks" ;
reverseWords(str);
|
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
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
void printWords(string str)
{
string word;
stringstream iss(str);
while (iss >> word) {
reverse(word.begin(), word.end());
cout << word << " " ;
}
}
int main()
{
string s = "GeeksforGeeks is good to learn" ;
printWords(s);
return 0;
}
|
Java
import java.io.*;
import java.lang.*;
import java.util.*;
class Main {
public static void printWords(String str)
{
String word;
StringTokenizer iss = new StringTokenizer(str);
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);
}
}
|
Python3
def print_words(s):
word = ""
iss = s.split()
for i in iss:
word = i[:: - 1 ]
print (word, end = " " )
if __name__ = = '__main__' :
s = "GeeksforGeeks 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)
{
string word;
using ( var iss = new StringReader(str))
{
string line;
while ((line = iss.ReadLine()) != null ) {
foreach ( string w in line.Split( ' ' ))
{
word
= new string (w.Reverse().ToArray());
Console.Write(word + " " );
}
}
}
}
static void Main()
{
string s = "GeeksforGeeks is good to learn" ;
printWords(s);
}
}
|
Javascript
function printWords(str) {
let word;
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 + " " );
}
}
}
let s = "GeeksforGeeks 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 = "" ;
istringstream ss(str);
vector<string> words;
do {
string word;
ss >> word;
words.push_back(word);
} while (ss);
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;
}
|
Java
import java.util.Arrays;
import java.util.stream.Collectors;
public class reverseIndividual {
public static void main(String[] args) {
String str = "Welcome to GFG" ;
String result = Arrays.asList(str.split( " " ))
.stream()
.map(s -> new StringBuilder(s).reverse())
.collect(Collectors.joining( " " ));
System.out.println(result);
}
}
|
Python3
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 ))
|
C#
using System;
using System.Linq;
public class ReverseIndividual
{
public static void Main( string [] args)
{
string str = "Welcome to GFG" ;
string result = string .Join( " " , str.Split( ' ' )
.Select(word => new string (word.Reverse().ToArray())));
Console.WriteLine(result);
}
}
|
Javascript
function reverseIndividualWords(str) {
const words = str.split( ' ' );
const reversedWords = words.map(word => word.split( '' ).reverse().join( '' ));
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
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));
}
}
|
Python3
def make_reverse(string: str ) - > str :
string = string[:: - 1 ]
rev = string.split( " " )
rev = rev[:: - 1 ]
reversed_string = " " .join(rev)
return reversed_string
if __name__ = = "__main__" :
string = "Geeks for Geeks"
print (make_reverse(string))
|
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
function makeReverse(string) {
string = string.split( "" ).reverse().join( "" );
let rev = string.split( " " );
rev = rev.reverse();
let reversedString = rev.join( " " );
return reversedString;
}
let string = "Geeks for Geeks" ;
console.log(makeReverse(string));
|
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 :
std::string reverse(std::string str) {
std::stack< char > s;
for ( int i = 0; i < str.length(); i++)
s.push(str[i]);
std::string rev = "" ;
std::string temp = "" ;
while (!s.empty()) {
if ( isalpha (s.top()))
temp += s.top();
else {
rev = " " + temp + rev;
temp = "" ;
}
s.pop();
}
if (!temp.empty())
rev = temp + rev;
return rev;
}
};
int main() {
std::string str = "Geeks for Geeks" ;
Reverse obj;
std::cout << obj.reverse(str) << std::endl;
return 0;
}
|
Java
import java.util.Stack;
public class Reverse {
String reverse(String str)
{
Stack<Character> s = new Stack<>();
for ( int i = 0 ; i < str.length(); i++)
s.push(str.charAt(i));
String rev = "" ;
String temp = "" ;
while (!s.isEmpty()) {
if (Character.isLetter(s.peek()))
temp = temp + s.pop();
else {
rev = " " + temp + rev;
temp = "" ;
s.pop();
}
}
if (temp != "" )
rev = temp + rev;
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:
def reverse( self , string):
stack = []
for i in range ( len (string)):
stack.append(string[i])
rev = ""
temp = ""
while len (stack) > 0 :
if stack[ - 1 ].isalpha():
temp = temp + stack.pop()
else :
rev = " " + temp + rev
temp = ""
stack.pop()
if temp ! = "":
rev = temp + rev
return rev
if __name__ = = '__main__' :
str = "Geeks for Geeks"
obj = Reverse()
print (obj.reverse( str ))
|
C#
using System;
using System.Collections.Generic;
class Reverse
{
public string ReverseWords( string str)
{
Stack< char > stack = new Stack< char >();
for ( int i = 0; i < str.Length; i++)
{
stack.Push(str[i]);
}
string rev = "" ;
string temp = "" ;
while (stack.Count > 0)
{
if ( char .IsLetter(stack.Peek()))
{
temp += stack.Pop();
}
else
{
rev = " " + temp + rev;
temp = "" ;
stack.Pop();
}
}
if (! string .IsNullOrEmpty(temp))
{
rev = temp + rev;
}
return rev;
}
}
class Program
{
static void Main()
{
string str = "Geeks for Geeks" ;
Reverse obj = new Reverse();
Console.WriteLine(obj.ReverseWords(str));
Console.ReadLine();
}
}
|
Javascript
class Reverse {
reverse(str) {
const stack = [];
for (let i = 0; i < str.length; i++) {
stack.push(str.charAt(i));
}
let rev = '' ;
let temp = '' ;
while (stack.length > 0) {
if (/[a-zA-Z]/.test(stack[stack.length - 1])) {
temp += stack.pop();
}
else {
rev = ' ' + temp + rev;
temp = '' ;
stack.pop();
}
}
if (temp !== '' ) {
rev = temp + rev;
}
return rev;
}
}
const str = 'Geeks for Geeks' ;
const obj = new Reverse();
console.log(obj.reverse(str));
|
Time Complexity : O(N)
Auxiliary Space : O(N) for using stack .
Way 5 : Using Split and iterator
Implementation:
Java
public class ReverseSentence {
public static String revSentence(String sentence) {
String[] words = sentence.split( " " );
StringBuilder reverseSentence = new StringBuilder();
for (String word : words) {
reverseSentence.append( new StringBuilder(word).reverse().toString()).append( " " );
}
return reverseSentence.toString().trim();
}
public static void main(String[] args) {
String input = "geeks quiz practice code" ;
System.out.println(revSentence(input));
}
}
|
Python3
def rev_sentence(sentence):
words = sentence.split( ' ' )
reverse_sentence = ""
for i in words:
reverse_sentence + = i[:: - 1 ] + ' '
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:
Python3
s = " Geeks for Geeks"
l = []
s = s.split()
for i in s:
l.append(i[:: - 1 ])
print ( " " .join(l))
|
Output
skeeG rof skeeG
Time Complexity: O(n)
Auxiliary Space: O(n)
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
30 Nov, 2023
Like Article
Save Article