Print words of a string in reverse order
Last Updated :
21 Jul, 2022
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 specifier" .
Property: %s will get all the values until it gets NULL i.e. '\0'.
Example: char String[] = "I AM A GEEK" is stored as shown in the image below :

Approach: Traverse the string from the last character, and move towards the first character. While traversing, if a space character is encountered, put a NULL in that position and print the remaining string just after the NULL character. Repeat this until the loop is over and when the loop ends, print the string, the %s will make the printing of characters until it encounters the first NULL character.
Let us see the approach with the help of diagrams:
step 1: Traverse from the last character until it encounters a space character .

Step 2: Put a NULL character at the position of space character and print the string after it.

Step 3: At the end, the loop ends when it reaches the first character, so print the remaining characters, it will be printed the first NULL character, hence the first word will be printed.

Implementation:
C++
// C++ program to print reverse
// of words in a string.
#include <iostream>
using namespace std;
string wordReverse(string str)
{
int i = str.length() - 1;
int start, end = i + 1;
string result = "";
while (i >= 0) {
if (str[i] == ' ') {
start = i + 1;
while (start != end)
result += str[start++];
result += ' ';
end = i;
}
i--;
}
start = 0;
while (start != end)
result += str[start++];
return result;
}
// Driver code
int main()
{
string str = "I AM A GEEK";
cout << wordReverse(str);
return 0;
}
// This code is contributed
// by Imam
C
// C program to print reverse of words in
// a string.
#include <stdio.h>
#include <string.h>
void printReverse(char str[])
{
int length = strlen(str);
// Traverse string from end
int i;
for (i = length - 1; i >= 0; i--) {
if (str[i] == ' ') {
// putting the NULL character at the
// position of space characters for
// next iteration.
str[i] = '\0';
// Start from next character
printf("%s ", &(str[i]) + 1);
}
}
// printing the last word
printf("%s", str);
}
// Driver code
int main()
{
char str[] = "I AM A GEEK";
printReverse(str);
return 0;
}
Java
// Java program to print reverse
// of words in a string.
import java.io.*;
import java.lang.*;
import java.util.*;
class GFG {
static String wordReverse(String str)
{
int i = str.length() - 1;
int start, end = i + 1;
String result = "";
while (i >= 0) {
if (str.charAt(i) == ' ') {
start = i + 1;
while (start != end)
result += str.charAt(start++);
result += ' ';
end = i;
}
i--;
}
start = 0;
while (start != end)
result += str.charAt(start++);
return result;
}
// Driver code
public static void main(String[] args)
{
String str = "I AM A GEEK";
System.out.print(wordReverse(str));
}
}
// This code is contributed
// by Akanksha Rai(Abby_akku)
Python3
# Python3 program to print reverse
# of words in a string.
def wordReverse(str):
i = len(str)-1
start = end = i+1
result = ''
while i >= 0:
if str[i] == ' ':
start = i+1
while start != end:
result += str[start]
start += 1
result += ' '
end = i
i -= 1
start = 0
while start != end:
result += str[start]
start += 1
return result
# Driver Code
str = 'I AM A GEEK'
print(wordReverse(str))
# This code is contributed
# by SamyuktaSHegde
C#
// C# program to print reverse
// of words in a string.
using System;
class GFG {
static String wordReverse(String str)
{
int i = str.Length - 1;
int start, end = i + 1;
String result = "";
while (i >= 0) {
if (str[i] == ' ') {
start = i + 1;
while (start != end)
result += str[start++];
result += ' ';
end = i;
}
i--;
}
start = 0;
while (start != end)
result += str[start++];
return result;
}
// Driver code
public static void Main()
{
String str = "I AM A GEEK";
Console.Write(wordReverse(str));
}
}
// This code is contributed
// by Akanksha Rai(Abby_akku)
PHP
<?php
// PHP program to print reverse
// of words in a string
function wordReverse($str)
{
$i = strlen($str) - 1;
$end = $i + 1;
$result = "";
while($i >= 0)
{
if($str[$i] == ' ')
{
$start = $i + 1;
while($start != $end)
$result = $result . $str[$start++];
$result = $result . ' ';
$end = $i;
}
$i--;
}
$start = 0;
while($start != $end)
$result = $result . $str[$start++];
return $result;
}
// Driver code
$str = "I AM A GEEK";
echo wordReverse($str);
// This code is contributed by ita_c
?>
JavaScript
<script>
// Javascript program to print reverse
// of words in a string.
function wordReverse(str)
{
var i = str.length - 1;
var start, end = i + 1;
var result = "";
while (i >= 0)
{
if (str[i] == ' ')
{
start = i + 1;
while (start != end)
result += str[start++];
result += ' ';
end = i;
}
i--;
}
start = 0;
while (start != end)
result += str[start++];
return result;
}
// Driver code
var str = "I AM A GEEK";
document.write(wordReverse(str));
// This code is contributed by rutvik_56
</script>
Time Complexity: O(len(str))
Auxiliary Space: O(len(str))
Without using any extra space:
Go through the string and mirror each word in the string, then, at the end, mirror the whole string.





Implementation: The following C++ code can handle multiple contiguous spaces.
C++
#include <algorithm>
#include <iostream>
#include <string>
using namespace std;
string reverse_words(string s)
{
int left = 0, i = 0, n = s.length();
while (s[i] == ' '){
i++;
}
left = i;
while (i < n)
{
if (i + 1 == n || s[i] == ' ')
{
int j = i - 1;
if (i + 1 == n)
j++;
reverse(s.begin()+left, s.begin()+j+1);
left = i + 1;
}
if (left < n && s[left] == ' ' && i > left)
left = i;
i++;
}
// reversing the string
reverse(s.begin(), s.end());
return s;
}
int main()
{
string str = "I AM A GEEK";
str = reverse_words(str);
cout << str;
return 0;
// This code is contributed
// by Gatea David
}
Java
/*package whatever //do not write package name here */
import java.io.*;
class GFG {
static String reverse_words(String s)
{
int left = 0, i = 0, n = s.length();
while (s.charAt(i) == ' '){
i++;
}
left = i;
while (i < n)
{
if (i + 1 == n || s.charAt(i) == ' ')
{
int j = i - 1;
if (i + 1 == n)
j++;
while (left<n && j<n && left < j){
char ch[] = s.toCharArray();
char temp = ch[left];
ch[left] = ch[j];
ch[j] = temp;
s = String.valueOf(ch);
left++;
j--;
}
left = i + 1;
}
if (left < n && s.charAt(left) == ' ' && i > left)
left = i;
i++;
}
// reversing the string
char ch[] = s.toCharArray();
int len = s.length();
for (i=0; i < (len/2); i++)
{
char temp = ch[i];
ch[i] = ch[len - i - 1];
ch[len - i- 1] = temp;
}
s = String.valueOf(ch);
return s;
}
public static void main(String args[])
{
String str = "I AM A GEEK";
str = reverse_words(str);
System.out.println(str);
}
}
// This code is contributed by shinjanpatra.
Python3
# Python code for the same approach
def reverse_words(s):
left, i, n = 0, 0, len(s)
while (s[i] == ' '):
i += 1
left = i
while (i < n):
if (i + 1 == n or s[i] == ' '):
j = i - 1
if (i + 1 == n):
j += 1
while (left < j):
s = s[0:left] + s[j] + s[left+1:j] + s[left] + s[j+1:]
left += 1
j -= 1
left = i + 1
if (i > left and s[left] == ' '):
left = i
i += 1
s = s[::-1]
return s
# driver code
Str = "I AM A GEEK"
Str = reverse_words(Str)
print(Str)
# This code is contributed by shinjanpatra
C#
// C# program to print reverse
// of words in a string.
using System;
class GFG {
static String reverse_words(String s)
{
var left = 0;
var i = 0;
var n = s.Length;
while (s[i] == ' ') {
i++;
}
left = i;
while (i < n) {
if (i + 1 == n || s[i] == ' ') {
var j = i - 1;
if (i + 1 == n) {
j++;
}
while (left < n && j < n && left < j) {
char[] ch = s.ToCharArray();
var temp = ch[left];
ch[left] = ch[j];
ch[j] = temp;
s = new string(ch);
left++;
j--;
}
left = i + 1;
}
if (left < n && s[left] == ' ' && i > left) {
left = i;
}
i++;
}
// reversing the string
int len = s.Length;
char[] chh = s.ToCharArray();
for (i = 0; i < (len / 2); i++) {
char temp = chh[i];
chh[i] = chh[len - i - 1];
chh[len - i - 1] = temp;
}
s = new string(chh);
return s;
}
public static void Main(String[] args)
{
string str = "I AM A GEEK";
str = reverse_words(str);
Console.WriteLine(str);
}
}
// This code is contributed by Aarti_Rathi
JavaScript
<script>
// JavaScript code for the approach
function reverse_words(s)
{
let left = 0, i = 0, n = s.length;
while (s[i] == ' ')
i++;
left = i;
while (i < n)
{
if (i + 1 == n || s[i] == ' ')
{
let j = i - 1;
if (i + 1 == n)
j++;
let temp;
let a = s.split("");
while (left < j){
temp = a[left];
a[left] = a[j];
a[j] = temp;
left++;
j--;
}
s = a.join("");
left = i + 1;
}
if (s[left] == ' ' && i > left)
left = i;
i++;
}
s = s.split('').reverse().join('');
return s;
}
// driver code
let str = "I AM A GEEK";
str = reverse_words(str);
document.write(str);
// This code is contributed by shinjanpatra
</script>
Time Complexity: O(len(str))
Auxiliary Space: O(1)
Similar Reads
Reverse words in a string
Given a string str, your 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.p
11 min read
Reverse Words in a Given String in Python
In this article, we explore various ways to reverse the words in a string using Python. From simple built-in methods to advanced techniques like recursion and stacks. We are going to see various techniques to reverse a string.Using split() and join()Using split() and join() is the most common method
2 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 J
3 min read
Reverse vowels in a given string
Given a string s, reverse only the vowels in s while keeping the other characters in their original positions.Examples:Input: "geeksforgeeks"Output: "geeksforgeeks"Explanation: The vowels 'e', 'e', 'o', 'e', 'e' are reversed, resulting in "geeksforgeeks".Input: "helloworld"Output: "hollowerld"Explan
9 min read
Print reverse string after removing vowels
Given a string s, print reverse of string and remove the characters from the reversed string where there are vowels in the original string. Examples: Input : geeksforgeeksOutput : segrfsegExplanation :Reversed string is skeegrofskeeg, removing characters from indexes 1, 2, 6, 9 & 10 (0 based ind
13 min read
Find the first repeated word in a string
Given a string, Find the 1st repeated word in a string. Examples: Input: "Ravi had been saying that he had been there"Output: hadInput: "Ravi had been saying that"Output: No Repetition Input: "he had had he" he question source: https://www.geeksforgeeks.org/goldman-sachs-interview-experience-set-29-
15+ min read
Print reverse of a string using recursion
Given a string, the task is to print the given string in reverse order using recursion.Examples:Input: s = "Geeks for Geeks"Output: "skeeG rof skeeG"Explanation: After reversing the input string we get "skeeG rof skeeG". Input: s = "Reverse a string Using Recursion"Output: "noisruceR gnisU gnirts a
5 min read
C++ STL - Vector in Reverse Order
Prerequisite: Vectors in C++ A vector can be printed in reverse order with the following methods: By traversing in the backward direction using indexingBy traversing in the backward direction using begin() and end() functions in C++ STLBy traversing in the backward direction using rbegin() and rend(
3 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 = "pra
4 min read
How to reverse a String in Python
Reversing a string is a common task in Python, which can be done by several methods. In this article, we discuss different approaches to reversing a string. One of the simplest and most efficient ways is by using slicing. Letâs see how it works:Using string slicingThis slicing method is one of the s
4 min read