Print words of a string in reverse order - GeeksforGeeks

08 Mar, 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.
C++
C
Java
Python3
C#
PHP
Javascript
// 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 codeint main(){    string str = "I AM A GEEK";     cout << wordReverse(str);     return 0;} // This code is contributed// by Imam
// 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 codeint main(){    char str[] = "I AM A GEEK";    printReverse(str);    return 0;}
// 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 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 Codestr = 'I AM A GEEK'print(wordReverse(str)) # This code is contributed# by SamyuktaSHegde
// 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 program to print reverse// of words in a stringfunction 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?>
<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 codevar str = "I AM A GEEK"; document.write(wordReverse(str)); // This code is contributed by rutvik_56 </script>
Output: 
GEEK A AM I
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.
The following C++ code can handle multiple contiguous spaces.
C++
Javascript
#include <algorithm>#include <iostream>#include <string> using namespace std; string reverse_words(string s){    int left = 0, i = 0, n = s.size();       while (s[i] == ' ')        i++;       left = i;       while (i < n)    {        if (i + 1 == n || s[i] == ' ')        {            int j = i - 1;            if (i + 1 == n)                j++;                       while (left < j)                swap(s[left++], s[j--]);                       left = i + 1;        }        if (s[left] == ' ' && i > left)            left = i;               i++;    }    //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}
<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>
Output:
GEEK A AM I
Time Complexity: O(len(str))
Auxiliary Space: O(1)
This article is contributed by MAZHAR IMAM KHAN. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Imam
Akanksha_Rai
SamyuktaSHegde
ukasp
subhammahato348
rutvik_56
gulshankumarar231
simmytarika5
davidgatea21
shinjanpatra
Mentor Graphics
Reverse
Strings
Technical Scripter
Strings
Reverse
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Check for Balanced Brackets in an expression (well-formedness) using Stack
Python program to check if a string is palindrome or not
KMP Algorithm for Pattern Searching
Convert string to char array in C++
Longest Palindromic Substring | Set 1
Array of Strings in C++ (5 Different Ways to Create)
Caesar Cipher in Cryptography
Check whether two strings are anagram of each other
Top 50 String Coding Problems for Interviews
Length of the longest substring without repeating characters