The Wayback Machine - https://web.archive.org/web/20240917105056/https://www.geeksforgeeks.org/reverse-words-in-a-given-string/
Open In App

Reverse words in a string

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

Given a string, the task is to reverse the order of the words in the given string. 

Examples:

Input: s = “i love programming very much” 
Output: s = “much very programming love i” 

Input: s = ” geeks for all” 
Output: s = “all for geeks”
We need to remove all the extra spaces in the output

Using Split, Reverse and Join:

We follow the three steps mentioned below.

  1. Split the given string into an array of words. For example, ” geeks for all” is spitted as {“geeks”, “for”, “all”}
  2. Reverse the array of words. We get {“all”, “for”, “geeks”}
  3. Join the reversed array back into a string. We get “all for geeks”

Below is the implementation of the above approach:

C++
#include <bits/stdc++.h>
using namespace std;

void reverseWords(string& str)
{
    // Split the string into an
    // of words
    istringstream ss(str);
    string word; 
    vector<string> arr;
    while (ss >> word) 
      arr.push_back(word);
      
    // Reverse array of words  
    reverse(arr.begin(), arr.end());  
      
    // Join the words in reverse order  
    str = "";  
    for (string &s : arr) 
        str += (s + " "); 
}

// Driver code
int main()
{
    string str = "  geeks for all";
    reverseWords(str);
    cout << str;
    return 0;
}
Java
import java.util.*;

class GfG {
    static String reverseWords(String text) {
        String[] str = text.split(" ");
        Collections.reverse(Arrays.asList(str));
        return String.join(" ", str);
    }
  
    public static void main(String[] args) {
        String text = "  geeks for all";
        System.out.println(reverseWords(text));
    }
}
Python
def reverse_words(string):
  
    # Split words in the given string
    # and reverse the order
    reversed_words = string.split()[::-1]
    
    # Join the reversed words into a 
    # single string
    return " ".join(reversed_words)

# Input string
string = " geeks for all"
print(reverse_words(string))
C#
using System;
using System.Linq;

public class GfG {
    static public void Main() {
        string text = "   geeks for all";
        Console.WriteLine(ReverseWords(text));
    }

    static string ReverseWords(string text) {
        return string.Join(" ", text.Split(' ').Reverse());
    }
}
JavaScript
function reverseWords(text) {
    let str = text.split(" ");
    str.reverse();
    return str.join(" ");
}

let text = "   geeks for all";
console.log(reverseWords(text));
PHP
<?php
function reverseWords($string) {
    $array = explode(" ", $string);
    $rarray = array_reverse($array);
    return implode(" ", $rarray);
}

$string = "  geeks for all";
echo reverseWords($string);
?>

Output
all for geeks 

Using Stack

  1. Push all words separated by a space into a stack.
  2. Set the string as empty.
  3. Pop all words one by one from stack and append back into the string.

Below is the implementation of the above approach: 

C++
#include <bits/stdc++.h>
using namespace std;

// Function to reverse words
void reverseWords(string s)
{
    // Create a stack and pusb all words
    // one by one
    stack<string> st;
    string str = "";
    for (int i = 0; i < s.length(); i++)
    {

        if (s[i] != ' ')
            str += s[i];

        // If we see a space, we push the
        // previously seen word into the stack.
        else if (!str.empty())
        {
            st.push(str);
            str = "";
        }
    }

    // Last word remaining, add it to stack
    if (!str.empty())
        st.push(str);
 
    // Now print from top to bottom of the stack
    while (!st.empty())
    {
        cout << st.top();
        st.pop();
        if (!st.empty())
            cout << " ";
    }
}

// Driver Code
int main()
{
    string s = "  geeks for all";
    reverseWords(s);
    return 0;
}
C
#include <stdio.h>
#include <string.h>

// Function to reverse words
void reverseWords(char* s) {
  
    // Create a stack and push all words one by one
    char* stack[100];
    int top = -1;
    char* token = strtok(s, " ");
    
    // Traverse the string and split words
    while (token != NULL) {
        stack[++top] = token;
        token = strtok(NULL, " ");
    }

    // Now print from top to bottom of the stack
    while (top >= 0) {
        printf("%s", stack[top--]);
        if (top >= 0)
            printf(" ");
    }
}

int main() {
    char s[] = "  geeks for all";
    reverseWords(s);
    return 0;
}
Java
import java.util.ArrayDeque;
import java.util.Deque;

class GfG {

    // Function to reverse words
    public static void reverseWords(String s) {
      
        // Create a deque and push all words one by one
        Deque<String> st = new ArrayDeque<>();
        StringBuilder str = new StringBuilder();
        
        // Traverse the string and split words
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) != ' ')
                str.append(s.charAt(i));
          
            // If we see a space, push the
            // previously seen word into the deque
            else if (str.length() > 0) {
                st.push(str.toString());
                str.setLength(0);
            }
        }
        // Last word remaining, add it to deque
        if (str.length() > 0)
            st.push(str.toString());

        // Now print from top to bottom of the deque
        while (!st.isEmpty()) {
            System.out.print(st.pop());
            if (!st.isEmpty())
                System.out.print(" ");
        }
    }
  
    public static void main(String[] args) {
        String s = "  geeks for all";
        reverseWords(s);
    }
}
Python
# Function to reverse words
def reverse_words(s):
  
    # Create a stack and push all
    # words one by one
    stack = []
    word = ""
    
    # Traverse the string and split words
    for char in s:
        if char != ' ':
            word += char
            
        # If we see a space, push the
        # previously seen word into the stack
        elif word:
            stack.append(word)
            word = ""
    
    # Last word remaining, add it to stack
    if word:
        stack.append(word)
    
    # Now print from top to bottom of the stack
    while stack:
        print(stack.pop(), end=" ")

# Input string
string = "  geeks for all"
reverse_words(string)
C#
using System;
using System.Collections.Generic;

class GfG {

  // Function to reverse words
    static void reverseWords(string s) {
      
        // Create a stack and push all words one by one
        Stack<string> st = new Stack<string>();
        string str = "";
        
        // Traverse the string and split words
        foreach (char c in s) {
            if (c != ' ')
                str += c;
          
            // If we see a space, push the previously
            // seen word into the stack
            else if (str.Length > 0) {
                st.Push(str);
                str = "";
            }
        }
        // Last word remaining, add it to stack
        if (str.Length > 0)
            st.Push(str);

        // Now print from top to bottom of the stack
        while (st.Count > 0) {
            Console.Write(st.Pop());
            if (st.Count > 0)
                Console.Write(" ");
        }
    }
    public static void Main() {
        string s = "  geeks for all";
        reverseWords(s);
    }
}
JavaScript
// Function to reverse words
function reverseWords(s) {

    // Create a stack and push all words one by one
    let stack = [];
    let str = "";

    // Traverse the string and split words
    for (let i = 0; i < s.length; i++) {
        if (s[i] !== ' ') {
            str += s[i];
        }
        
        // If we see a space, push the previously
        // seen word into the stack
        else if (str.length > 0) {
            stack.push(str);
            str = "";
        }
    }
    // Last word remaining, add it to stack
    if (str.length > 0) {
        stack.push(str);
    }

    // Now print from top to bottom of the stack
    while (stack.length > 0) {
        process.stdout.write(stack.pop());
        if (stack.length > 0)
            process.stdout.write(" ");
    }
}

// Input string
let s = "  geeks for all";
reverseWords(s);

Output
all for geeks

Time complexity: O(n)
Auxiliary Space: O(n)

In this method, we can also use library methods to split as we have show in the first approach.

Using Two Reverses:

This solution works in O(1) auxiliary space and has mainly two steps.

  1. We first reverse individual words of the given string. For example if the given string is “geeks for all” would become “skeeg rof lla”
  2. Then we reverse the whole string. The string “skeeg rof lla” would become “all for geeks” 
C++
#include <bits/stdc++.h>
using namespace std;

// Function to reverse a sequence from "begin"
// index to "end" index
void reverse(string& s, int begin, int end) {
    while (begin < end) {
        swap(s[begin++], s[end--]);
    }
}

// Function to reverse individual words in a string
void reverseWords(string& s) {
    int word_begin = -1;

    // STEP 1. Reverse each word in the string
    for (int i = 0; i < s.size(); i++) {
      
        // Beginning of a word
        if (word_begin == -1 && s[i] != ' ') {
            word_begin = i;
        }
      
        // End of a word
        if (word_begin != -1 && (s[i + 1] == ' ' 
                       || i + 1 == s.size())) {
            reverse(s, word_begin, i);
            word_begin = -1;
        }
    }
  
    

    /*STEP 2 of the above algorithm */
    reverse(s, 0, s.size() - 1);
}

// Driver Code
int main() {
  
    string s = "  geeks for all";
    reverseWords(s);
    cout << s;
    return 0;
}
C
#include <stdio.h>
#include <string.h>

// Function to reverse a sequence from "begin" 
// index to "end" index
void reverse(char* s, int begin, int end) {
    while (begin < end) {
        char temp = s[begin];
        s[begin++] = s[end];
        s[end--] = temp;
    }
}

// Function to reverse individual words in a string
void reverseWords(char* s) {
    int word_begin = -1;

    // STEP 1. Reverse each word in the string
    for (int i = 0; i < strlen(s); i++) {
      
        // Beginning of a word
        if (word_begin == -1 && s[i] != ' ') {
            word_begin = i;
        }
      
        // End of a word
        if (word_begin != -1 && 
            (s[i + 1] == ' ' || 
             i + 1 == strlen(s))) {
          
            reverse(s, word_begin, i);
            word_begin = -1;
        }
    }

    // STEP 2. Reverse the entire string
    reverse(s, 0, strlen(s) - 1);
}

// Driver Code
int main() {
    char s[] = "  geeks for all";
    reverseWords(s);
    printf("%s", s);
    return 0;
}
Java
public class GfG {

    // Function to reverse a sequence from "begin" 
    // index to "end" index
    public static void reverse(char[] s, int begin, int end) {
        while (begin < end) {
            char temp = s[begin];
            s[begin++] = s[end];
            s[end--] = temp;
        }
    }

    // Function to reverse individual words in a string
    static void reverseWords(char[] s) {
        int wordBegin = -1;

        // STEP 1. Reverse each word in the string
        for (int i = 0; i < s.length; i++) {
            
            // Beginning of a word
            if (wordBegin == -1 && s[i] != ' ') {
                wordBegin = i;
            }
            
            // End of a word
            if (wordBegin != -1 && 
                (i + 1 == s.length || 
                 s[i + 1] == ' ')) {
              
                reverse(s, wordBegin, i);
                wordBegin = -1;
            }
        }

        // STEP 2. Reverse the entire string
        reverse(s, 0, s.length - 1);
    }

    // Driver Code
    public static void main(String[] args) {
        String str = "  geeks for all";
        char[] s = str.toCharArray();
        reverseWords(s);
        System.out.println(new String(s));
    }
}
Python
# Function to reverse individual words 
# in a string
def reverse_words(s):
    word_begin = -1

    # STEP 1. Reverse each word in the string
    for i in range(len(s)):
        
        # Beginning of a word
        if word_begin == -1 and s[i] != ' ':
            word_begin = i
        
        # End of a word
        if word_begin != -1 and (i + 1 == len(s) or s[i + 1] == ' '):
            reverse(s, word_begin, i)
            word_begin = -1

    # STEP 2. Reverse the entire string
    reverse(s, 0, len(s) - 1)
    
# Function to reverse a sequence from
# "begin" index to "end" index
def reverse(s, begin, end):
    while begin < end:
        s[begin], s[end] = s[end], s[begin]
        begin += 1
        end -= 1
        
# Driver Code
s = list("  geeks for all")
reverse_words(s)
print("".join(s))
C#
using System;

class GfG {

    // Function to reverse a sequence from "begin" 
    // index to "end" index
    public static void Reverse(char[] s, int begin, 
                               int end) {
        while (begin < end) {
            char temp = s[begin];
            s[begin++] = s[end];
            s[end--] = temp;
        }
    }

    // Function to reverse individual words in a string
    public static void ReverseWords(char[] s) {
        int wordBegin = -1;

        // STEP 1. Reverse each word in the string
        for (int i = 0; i < s.Length; i++) {
            
            // Beginning of a word
            if (wordBegin == -1 && s[i] != ' ') {
                wordBegin = i;
            }
            
            // End of a word
            if (wordBegin != -1 && 
                (i + 1 == s.Length || 
                 s[i + 1] == ' ')) {
                Reverse(s, wordBegin, i);
                wordBegin = -1;
            }
        }

        // STEP 2. Reverse the entire string
        Reverse(s, 0, s.Length - 1);
    }

    // Driver Code
    public static void Main() {
        string str = "  geeks for all";
        char[] s = str.ToCharArray();
        ReverseWords(s);
        Console.WriteLine(new string(s));
    }
}
JavaScript
// Function to reverse any sequence
// starting with pointer begin and
// ending with pointer end
function reverse(s, begin, end) {
    while (begin < end) {
        let charArray = [...s];
        let temp = charArray[begin];
        charArray[begin] = charArray[end];
        charArray[end] = temp;
        begin++;
        end--;
        s = charArray.join("");
    }
    return s;
}

function reverseWords(s) {
    let word_begin = -1;

    //  /* temp is for word boundary */
    let i = 0;

    /*STEP 1 of the above algorithm */
    while (i < s.length) {

        /*This condition is to make sure that the
          string start with valid character (not
          space) only*/
        if ((word_begin == -1) && (s[i] != ' ')) {
            word_begin = i;
        }
        if (word_begin != -1
            && ((s[i + 1] == ' ') || (i + 1 == s.length))) {
            s = reverse(s, word_begin, i);
            word_begin = -1;
        }
        i++;
    } /* End of while */

    /*STEP 2 of the above algorithm */
    s = reverse(s, 0, s.length - 1);
    return s;
}

// Driver Code
let s = "i like this program very much";

// Function call
s = reverseWords(s);
console.log(s);


// This code is contributed by akashish__

Output
all for geeks  

Time Complexity: O(n)
Auxiliary Space: O(1) 



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
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
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
Reverse individual words
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 befo
15+ 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
Create a new string by alternately combining the characters of two halves of the string in reverse
Given a string s, create a new string such that it contains the characters of the two halves of the string s combined alternately in reverse order. Examples: Input : s = carbohydratesOutput : hsoebtraarcdy Input : s = sunshineOutput : sennuish Explanation: Example 1: Two halves of the string carbohydrate are carboh and ydrates. As they needed to be
7 min read
Check if a given string is a Reverse Bitonic String or not
Given a string str, the task is to check if that string is a Reverse Bitonic string or not. If the string str is reverse Bitonic string, then print "YES". Otherwise, print "NO". A Reverse Bitonic String is a string in which the characters are arranged in decreasing order followed by increasing order of their ASCII values. Examples: Input: str = "zy
6 min read
Maximize cost of repeated removal of string P or its reverse from the string S
Given two positive integers X and Y and two numeric strings S and P of length N and 2 respectively, the task is to find the maximum total cost obtained by repeatedly removing string P or the reverse of the string P from the string S at the cost of X and Y respectively. Examples: Input: S = "12333444", X = 5, Y = 4, P = "34"Output: 15Explanation:Bel
11 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
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
Number of words that can be made using exactly P consonants and Q vowels from the given string
Given a string str and two integers P and Q. The task is to find the total count of words that can be formed by choosing exactly P consonants and Q vowels from the given string.Examples: Input: str = "geek", P = 1, Q = 1 Output: 8 "ge", "ge", "eg", "ek", "eg", "ek", "ke" and "ke" are the possible words.Input: str = "crackathon", P = 4, Q = 3 Output
7 min read
Least count of words required to construct a target String
Given an array of strings, words[] of size M and a string target of size N. The task is to find the minimum number of words required to spell out the string target by cutting individual letters from the collection of words and rearranging them, provided that there are infinite supplies of each word. If it is not possible, print -1. Examples: Input:
11 min read
Find least start index of a substring from given String that contains all the given words in a contiguous manner
Given a string S and an array of equal length words (strings) arr[]. The task is to find the minimum start index of the substring that contains all the given words in a contiguous manner. If no such index is found, return -1.Note: The words can be in any sequence. Examples: Input: arr[ ] = {"bat", "bal", "cat"}, S = "hellocatbyebalbatcatyo"Output:
9 min read
Count occurrences of strings formed using words in another string
Given a string A and a vector of strings B, the task is to count the number of strings in vector B that only contains the words from A. Examples: Input: A="blue green red yellow"B[]={"blue red", "green pink", "yellow green"}Output: 2 Input: A="apple banana pear"B[]={"apple", "banana apple", "pear banana"}Output: 3 Approach: Follow the below steps t
7 min read
Lexicographically largest string formed by choosing words from given Sentence as per given Pattern
Given a sentence S and a string B having distinct characters, find a string by joining the words of S according to given conditions:- Choose a word from S ifIt has at least length(B)/2 characters from string B orHaving at least one character from string B and lexicographically sorted in increasing order.The string formed should be lexicographically
7 min read
Remove Duplicate/Repeated words from String
Given a string S, the task is to remove all duplicate/repeated words from the given string. Examples: Input: S = "Geeks for Geeks A Computer Science portal for Geeks" Output: Geeks for A Computer Science portal Explanation: here 'Geeks' and 'for' are duplicate so these words are removed from the string Input: S = "Publish your own articles on Geeks
4 min read
Check if given words are present in a string
Given a big string and an array of small strings, all of which are smaller in length than the big string. The task is to create an array of booleans, where each boolean represents whether the small string at that index in the array of small strings is contained in the big string. Note : that you can't use language-built-in string-matching methods.
15+ min read
Program to extract words from a given String
The task is to extract words from a given string. There may be one or more space between words. Examples: Input : geeks for geeks Output : geeks for geeks Input : I love coding. Output: I love coding We have discussed a solution in the below post. How to split a string in C/C++, Python and Java? In this post, a new solution using stringstream is di
3 min read
Count words present in a string
Given an array of words and a string, we need to count all words that are present in given string. Examples: Input : words[] = { "welcome", "to", "geeks", "portal"} str = "geeksforgeeks is a computer science portal for geeks." Output : 2 Two words "portal" and "geeks" is present in str. Input : words[] = {"Save", "Water", "Save", "Yourself"} str =
6 min read
Check if a two character string can be made using given words
Given a string of two characters and n distinct words of two characters. The task is to find if it is possible to arrange given words in such a way that the concatenated string has the given two character string as a substring. We can append a word multiple times. Examples: Input : str = "ya" words[] = {"ah", "oy", "to", "ha"} Output : YES We can j
6 min read
Print all unique words of a String
Write a function that takes a String as an argument and prints all unique words in it. Examples: Input: Java is great. Grails is also greatOutput: Java Grails also Approach: The idea is to use the map to keep track of words already occurred. But first, we have to extract all words from a String, as a string may contain many sentences with punctuati
7 min read
Count words in a given string
Given a string, count the number of words in it. The words are separated by the following characters: space (' ') or new line ('\n') or tab ('\t') or a combination of these. Recommended PracticeCount number of wordsTry It!Method 1: The idea is to maintain two states: IN and OUT. The state OUT indicates that a separator is seen. State IN indicates t
15+ min read
Longest String Chain - Chain of words in an Array
Given an array of words where each word consists of lowercase English letters, wordA is a predecessor of wordB if and only if we can insert exactly one letter anywhere in wordA without changing the order of the other characters to make it equal to wordB, the task is to return the length of the longest possible word chain with words chosen from the
15+ min read
PHP | Reverse a String
PHP serves us with many built-in methods which can be used to manipulate strings. In this article, we will learn about how to reverse a string using various methods available in PHP. Examples: Input : GeeksforGeeks Output : skeeGrofskeeG Input : 12485 Output : 58421 Below we have discussed about three basic and most commonly used methods of reversi
3 min read
Reverse the given string in the range [L, R]
Given a string str, and two integers L and R, the task is to reverse the string in the range [L, R] i.e. str[L...R].Examples: Input: str = "geeksforgeeks", L = 5, R = 7 Output: geeksrofgeeks Reverse the characters in the range str[5...7] = "geeksforgeeks" and the new string will be "geeksrofgeeks" Input: str = "ijklmn", L = 1, R = 2 Output: ikjlmn
4 min read