Open In App

Reverse words in a given string

Last Updated : 13 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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

Examples:

Input: s = “geeks quiz practice code” 
Output: s = “code practice quiz geeks”

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

reverse-words

Approach:

  • Initially, reverse the individual words of the given string one by one, for the above example, after reversing individual words the string should be “i ekil siht margorp yrev hcum”.
  • Reverse the whole string from start to end to get the desired output “much very program this like i” in the above example.

Follow the below steps to solve the problem:

  • Run a for loop to traverse the string and create a temporary string to store the words
  • If the current character is a space then add the current string to the answer and empty the string
  • Else push the character into the string
  • Print the answer array in reverse order 

Below is the implementation of the above approach: 

C++




// C++ program to reverse a string
#include <bits/stdc++.h>
using namespace std;
 
// Function to reverse words*/
void reverseWords(string s)
{
 
    // temporary vector to store all words
    vector<string> tmp;
    string str = "";
    for (int i = 0; i < s.length(); i++) {
 
        // Check if we encounter space
        // push word(str) to vector
        // and make str NULL
        if (s[i] == ' ') {
            tmp.push_back(str);
            str = "";
        }
 
        // Else add character to
        // str to form current word
        else
            str += s[i];
    }
 
    // Last word remaining,add it to vector
    tmp.push_back(str);
 
    // Now print from last to first in vector
    int i;
    for (i = tmp.size() - 1; i > 0; i--)
        cout << tmp[i] << " ";
    // Last word remaining,print it
    cout << tmp[0] << endl;
}
 
// Driver Code
int main()
{
    string s = "i like this program very much";
    reverseWords(s);
    return 0;
}


C




// C program to reverse a string
#include <stdio.h>
 
// Function to reverse any sequence
// starting with pointer begin and
// ending with pointer end
void reverse(char* begin, char* end)
{
    char temp;
    while (begin < end) {
        temp = *begin;
        *begin++ = *end;
        *end-- = temp;
    }
}
 
// Function to reverse words*/
void reverseWords(char* s)
{
    char* word_begin = s;
 
    // Word boundary
    char* temp = s;
 
    // Reversing individual words as
    // explained in the first step
    while (*temp) {
        temp++;
        if (*temp == '\0') {
            reverse(word_begin, temp - 1);
        }
        else if (*temp == ' ') {
            reverse(word_begin, temp - 1);
            word_begin = temp + 1;
        }
    }
 
    // Reverse the entire string
    reverse(s, temp - 1);
}
 
// Driver Code
int main()
{
    char s[] = "i like this program very much";
    char* temp = s;
 
    // Driver code
    reverseWords(s);
    printf("%s", s);
    return 0;
}


Java




// Java program to
// reverse a String
import java.util.*;
class GFG {
 
    // Reverse the letters
    // of the word
    static void reverse(char str[], int start, int end)
    {
        // Temporary variable
        // to store character
        char temp;
 
        while (start <= end) {
            // Swapping the first
            // and last character
            temp = str[start];
            str[start] = str[end];
            str[end] = temp;
            start++;
            end--;
        }
    }
    // Function to reverse words
    static char[] reverseWords(char[] s)
    {
        // Reversing individual words as
        // explained in the first step
 
        int start = 0;
        for (int end = 0; end < s.length; end++) {
            // If we see a space, we
            // reverse the previous
            // word (word between
            // the indexes start and end-1
            // i.e., s[start..end-1]
            if (s[end] == ' ') {
                reverse(s, start, end);
                start = end + 1;
            }
        }
 
        // Reverse the last word
        reverse(s, start, s.length - 1);
 
        // Reverse the entire String
        reverse(s, 0, s.length - 1);
        return s;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        String s = "i like this program very much ";
 
        // Function call
        char[] p = reverseWords(s.toCharArray());
        System.out.print(p);
    }
}
 
// This code is contributed by gauravrajput1


Python3




# Python3 program to reverse a string
 
# Function to reverse each word in the string
 
 
def reverse_word(s, start, end):
    while start < end:
        s[start], s[end] = s[end], s[start]
        start = start + 1
        end -= 1
 
 
s = "i like this program very much"
 
# Convert string to list to use it as a char array
s = list(s)
start = 0
while True:
 
    # We use a try catch block because for
    # the last word the list.index() function
    # returns a ValueError as it cannot find
    # a space in the list
    try:
        # Find the next space
        end = s.index(' ', start)
 
        # Call reverse_word function
        # to reverse each word
        reverse_word(s, start, end - 1)
 
        # Update start variable
        start = end + 1
 
    except ValueError:
 
        # Reverse the last word
        reverse_word(s, start, len(s) - 1)
        break
 
# Reverse the entire list
s.reverse()
 
# Convert the list back to
# string using string.join() function
s = "".join(s)
 
print(s)
 
# Solution contributed by Prem Nagdeo


C#




// C# program to
// reverse a String
using System;
 
class GFG {
 
    // Reverse the letters
    // of the word
    static void reverse(char[] str, int start, int end)
    {
 
        // Temporary variable
        // to store character
        char temp;
 
        while (start <= end) {
 
            // Swapping the first
            // and last character
            temp = str[start];
            str[start] = str[end];
            str[end] = temp;
            start++;
            end--;
        }
    }
 
    // Function to reverse words
    static char[] reverseWords(char[] s)
    {
 
        // Reversing individual words as
        // explained in the first step
 
        int start = 0;
        for (int end = 0; end < s.Length; end++) {
 
            // If we see a space, we
            // reverse the previous
            // word (word between
            // the indexes start and end-1
            // i.e., s[start..end-1]
            if (s[end] == ' ') {
                reverse(s, start, end);
                start = end + 1;
            }
        }
 
        // Reverse the last word
        reverse(s, start, s.Length - 1);
 
        // Reverse the entire String
        reverse(s, 0, s.Length - 1);
        return s;
    }
 
    // Driver Code
    public static void Main(String[] args)
    {
        String s = "i like this program very much ";
        char[] p = reverseWords(s.ToCharArray());
        Console.Write(p);
    }
}
 
// This code is contributed by jana_sayantan


Javascript




<script>
    // Javascript program to
    // reverse a String
     
    // Reverse the letters
    // of the word
    function reverse(str,start,end)
    {
        // Temporary variable
        // to store character
        let temp;
         
         
        while (start <= end)
        {
            // Swapping the first
            // and last character
            temp = str[start];
            str[start]=str[end];
            str[end]=temp;
            start++;
            end--;
        }
    }
    // Function to reverse words
    function reverseWords(s)
    {
        // Reversing individual words as
        // explained in the first step
        s=s.split("");
        let start = 0;
        for (let end = 0; end < s.length; end++)
        {
            // If we see a space, we
            // reverse the previous
            // word (word between
            // the indexes start and end-1
            // i.e., s[start..end-1]
            if (s[end] == ' ')
            {
                reverse(s, start, end);
                start = end + 1;
            }
        }
        // Reverse the last word
        reverse(s, start, s.length - 1);
         
        // Reverse the entire String
        reverse(s, 0, s.length - 1);
        return s.join("");
    }
    // Driver Code
    var s = "i like this program very much ";
     
     
    document.write(reverseWords(s));
     
    // This code is contributed by avanitrachhadiya2155
</script>


Output

much very program this like i



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

Note: The above code doesn’t handle the cases when the string starts with space. 

Below is the implementation of the approach that handles this specific case and doesn’t make unnecessary calls to reverse function in the case of multiple spaces in between. Thanks to rka143 for providing this version. 

C++




// C++ program to reverse a string
#include <bits/stdc++.h>
using namespace std;
 
// Function to reverse any sequence
// starting with pointer begin and
// ending with pointer end
void reverse(string& s, int begin, int end)
{
 
    while (begin < end) {
        swap(s[begin++], s[end--]);
    }
}
 
// C++ program for above approach
 
void reverseWords(string& s)
{
    int word_begin = -1;
 
    //  /* temp is for word boundary */
    int i = 0;
 
    /*STEP 1 of the above algorithm */
    while (i < s.size()) {
 
        /*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.size()))) {
            reverse(s, word_begin, i);
            word_begin = -1;
        }
        i++;
    } /* End of while */
 
    /*STEP 2 of the above algorithm */
    reverse(s, 0, s.size() - 1);
}
 
// Driver Code
int main()
{
    string s = "i like this program very much";
 
    // Function call
    reverseWords(s);
    cout << s << endl;
    ;
    return 0;
}
 
// This code is contributed by garg28harsh.


C




// C program to reverse a string
#include <stdio.h>
 
// Function to reverse any sequence
// starting with pointer begin and
// ending with pointer end
void reverse(char* begin, char* end)
{
    char temp;
    while (begin < end) {
        temp = *begin;
        *begin++ = *end;
        *end-- = temp;
    }
}
 
// C program for above approach
 
void reverseWords(char* s)
{
    char* word_begin = NULL;
 
    //  /* temp is for word boundary */
    char* temp = s;
 
    /*STEP 1 of the above algorithm */
    while (*temp) {
 
        /*This condition is to make sure that the
          string start with valid character (not
          space) only*/
        if ((word_begin == NULL) && (*temp != ' ')) {
            word_begin = temp;
        }
        if (word_begin
            && ((*(temp + 1) == ' ')
                || (*(temp + 1) == '\0'))) {
            reverse(word_begin, temp);
            word_begin = NULL;
        }
        temp++;
    } /* End of while */
 
    /*STEP 2 of the above algorithm */
    reverse(s, temp - 1);
}
 
// Driver Code
int main()
{
    char s[] = "i like this program very much";
    char* temp = s;
   
      // Function call
    reverseWords(s);
    printf("%s", s);
    return 0;
}


Java




// Java program to reverse a string
import java.io.*;
 
class GFG {
  // Reverse the letters
  // of the word
  static void reverse(char[] str, int start, int end)
  {
    // Temporary variable
    // to store character
    char temp;
 
    while (start <= end) {
      // Swapping the first
      // and last character
      temp = str[start];
      str[start] = str[end];
      str[end] = temp;
      start++;
      end--;
    }
  }
 
  static char[] reverseWords(char[] s)
  {
    int word_begin = -1;
 
    //  /* temp is for word boundary */
    int 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
          && ((i + 1 == s.length)
              || (s[i + 1] == ' '))) {
        reverse(s, word_begin, i);
        word_begin = -1;
      }
      i++;
    } /* End of while */
 
    /*STEP 2 of the above algorithm */
    reverse(s, 0, (s.length - 1));
    return s;
  }
 
  // Driver Code
  public static void main(String[] args)
  {
    String s = "i like this program very much";
 
    // Function call
    char[] p = reverseWords(s.toCharArray());
    System.out.println(p);
  }
}
 
// This code is contributed by Srj_27.


Python3




# Python3 program to reverse a string
 
# Reverse the letters
# of the word
def reverse(str, start, end):
    # Temporary variable
    # to store character
    temp = ''
    str1 = ""
 
    while (start <= end):
        # Swapping the first
        # and last character
        temp = str[start]
        str[start] = str[end]
        str[end] = temp
        start+=1
        end-=1
    return str1.join(str)
 
def reverseWords(s):
     
    word_begin = -1
 
    #  temp is for word boundary
    i = 0
 
    # STEP 1 of the above algorithm
    while (i < len(s)):
 
        ''' This condition is to make sure that the
                string start with valid character (not
                space) only '''
        if ((word_begin == -1) and (s[i] != ' ')):
            word_begin = i
        if (word_begin != -1 and ((i + 1 == len(s)) or (s[i + 1] == ' '))):
            s = reverse(list(s), word_begin, i)
            word_begin = -1
        i+=1
    ''' End of while '''
 
    # STEP 2 of the above algorithm
    s = reverse(list(s), 0, (len(s) - 1))
    return s
 
# Driver Code
s = "i like this program very much"
 
# Function call
p = reverseWords(list(s))
print(p)
 
# This code is contributed by akashish__


C#




// C# program to reverse a string
using System;
class GFG
{
 
  // Reverse the letters
  // of the word
  static void reverse(char[] str, int start, int end)
  {
    // Temporary variable
    // to store character
    char temp;
 
    while (start <= end) {
      // Swapping the first
      // and last character
      temp = str[start];
      str[start] = str[end];
      str[end] = temp;
      start++;
      end--;
    }
  }
 
  static char[] reverseWords(char[] s)
  {
    int word_begin = -1;
 
    //  /* temp is for word boundary */
    int 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
          && ((i + 1 == s.Length)
              || (s[i + 1] == ' '))) {
        reverse(s, word_begin, i);
        word_begin = -1;
      }
      i++;
    } /* End of while */
 
    /*STEP 2 of the above algorithm */
    reverse(s, 0, (s.Length - 1));
    return s;
  }
 
  // Driver Code
  static void Main(string[] args)
  {
    String s = "i like this program very much";
 
    // Function call
    char[] p = reverseWords(s.ToCharArray());
    Console.WriteLine(p);
  }
}
 
// This code is contributed by Karandeep1234.


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

much very program this like i



Time Complexity: O(N)
Auxiliary Space: O(N) 

Approach: To solve the problem follow the below idea:

We can do the above task by splitting and saving the string in a reverse manner. 

Follow the below steps to solve the problem:

  • Store the string in the form of words
  • Run a for loop in reverse order to print the words accordingly 

Below is the implementation of the above approach:

C++




// C++ program to reverse a string
// s = input()
 
#include <bits/stdc++.h>
using namespace std;
 
int main()
{
    string s[] = { "i",       "like", "this",
                   "program", "very", "much" };
 
    string ans = "";
    for (int i = 5; i >= 0; i--) {
        ans += s[i] + " ";
    }
  
    cout << (ans.substr(0, ans.length() - 1)) << endl;
 
    return 0;
}


Java




// Java program to reverse a string
// s = input()
public class ReverseWords {
 
    public static void main(String[] args)
    {
        String s[]
            = "i like this program very much".split(" ");
        String ans = "";
        for (int i = s.length - 1; i >= 0; i--) {
            ans += s[i] + " ";
        }
         
        System.out.println(
            ans.substring(0, ans.length() - 1));
    }
}


Python3




# Python3 program to reverse a string
# s = input()
s = "i like this program very much"
words = s.split(' ')
string = []
for word in words:
    string.insert(0, word)
 
 
print(" ".join(string))
 
# Solution proposed bu Uttam


C#




// C# program to reverse a string
// s = input()
 
using System;
public class ReverseWords {
 
    public static void Main()
    {
        string[] s
            = "i like this program very much".Split(' ');
        string ans = "";
        for (int i = s.Length - 1; i >= 0; i--) {
            ans += s[i] + " ";
        }
         
        Console.Write(ans.Substring(0, ans.Length - 1));
    }
}


Javascript




<script>
 
// JavaScript program to reverse a string
 
var s= ["i", "like", "this", "program", "very", "much"];
                                         
    var ans ="";
    for (var i = 5; i >= 0; i--)
    {
        ans += s[i] + " ";
    }
     
    document.write(ans.slice(0,ans.length-1));
 
 
</script>


Output

much very program this like i



Time Complexity: O(N)
Auxiliary Space: O(N) 

Reverse words in a given string using the swap operation:

The above task can also be accomplished by splitting the words separately and directly swapping the string starting from the middle.

Follow the below steps to solve the problem:

  • Store the string in the form of words
  • Swap the words with each other starting from the middle
  • Print the string

Below is the implementation of the above approach:

C++




// C++ code to reverse a string
 
#include <bits/stdc++.h>
using namespace std;
 
// Reverse the string
string RevString(string s[], int l)
{
 
    // Check if number of words is even
    if (l % 2 == 0) {
 
        // Find the middle word
        int j = l / 2;
 
        // Starting from the middle
        // start swapping words at
        // jth position and l-1-j position
        while (j <= l - 1) {
            string temp;
            temp = s[l - j - 1];
            s[l - j - 1] = s[j];
            s[j] = temp;
            j += 1;
        }
    }
 
    // Check if number of words is odd
    else {
 
        // Find the middle word
        int j = (l / 2) + 1;
 
        // Starting from the middle start
        // swapping the words at jth
        // position and l-1-j position
        while (j <= l - 1) {
            string temp;
            temp = s[l - j - 1];
            s[l - j - 1] = s[j];
            s[j] = temp;
            j += 1;
        }
    }
 
    string S = s[0];
 
    // Return the reversed sentence
    for (int i = 1; i < 6; i++) {
        S = S + " " + s[i];
    }
    return S;
}
 
// Driver code
int main()
{
    string s = "i like this program very much";
 
    string words[]
        = { "i", "like", "this", "program", "very", "much" };
 
    cout << RevString(words, 6) << endl;
 
    return 0;
}


Java




// Java code to reverse a string
 
import java.io.*;
 
class GFG {
 
    // Reverse the string
    public static String[] RevString(String[] s, int l)
    {
        // Check if number of words is even
        if (l % 2 == 0) {
 
            // Find the middle word
            int j = l / 2;
 
            // Starting from the middle
            // start swapping words at
            // jth position and l-1-j position
            while (j <= l - 1) {
                String temp;
                temp = s[l - j - 1];
                s[l - j - 1] = s[j];
                s[j] = temp;
                j += 1;
            }
        }
 
        // Check if number of words is odd
        else {
 
            // Find the middle word
            int j = (l / 2) + 1;
 
            // Starting from the middle start
            // swapping the words at jth
            // position and l-1-j position
            while (j <= l - 1) {
                String temp;
                temp = s[l - j - 1];
                s[l - j - 1] = s[j];
                s[j] = temp;
                j += 1;
            }
        }
 
        // Return the reversed sentence
        return s;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        String s = "i like this program very much";
        String[] words = s.split("\\s");
 
        words = RevString(words, words.length);
 
        s = String.join(" ", words);
 
        System.out.println(s);
    }
}
 
// This code is contributed by MuskanKalra1


Python3




# Python3 code to reverse a string
 
# Reverse the string
 
 
def RevString(s, l):
 
    # Check if number of words is even
    if l % 2 == 0:
 
        # Find the middle word
        j = int(l/2)
 
        # Starting from the middle
        # start swapping words
        # at jth position and l-1-j position
        while(j <= l - 1):
            s[j], s[l - j - 1] = s[l - j - 1], s[j]
            j += 1
 
    # Check if number of words is odd
    else:
 
        # Find the middle word
        j = int(l/2 + 1)
 
        # Starting from the middle
        # start swapping the words
        # at jth position and l-1-j position
        while(j <= l - 1):
            s[j], s[l - 1 - j] = s[l - j - 1], s[j]
            j += 1
 
        # return the reversed sentence
        return s
 
 
# Driver Code
s = 'i like this program very much '
string = s.split(' ')
string = RevString(string, len(string))
print(" ".join(string))


C#




// C# code to reverse a string
using System;
class GFG {
 
    // Reverse the string
    static string RevString(string[] s, int l)
    {
 
        // Check if number of words is even
        if (l % 2 == 0) {
 
            // Find the middle word
            int j = l / 2;
 
            // Starting from the middle
            // start swapping words at
            // jth position and l-1-j position
            while (j <= l - 1) {
                string temp;
                temp = s[l - j - 1];
                s[l - j - 1] = s[j];
                s[j] = temp;
                j += 1;
            }
        }
 
        // Check if number of words is odd
        else {
 
            // Find the middle word
            int j = (l / 2) + 1;
 
            // Starting from the middle start
            // swapping the words at jth
            // position and l-1-j position
            while (j <= l - 1) {
                string temp;
                temp = s[l - j - 1];
                s[l - j - 1] = s[j];
                s[j] = temp;
                j += 1;
            }
        }
 
        string S = s[0];
 
        // Return the reversed sentence
        for (int i = 1; i < 6; i++) {
            S = S + " " + s[i];
        }
        return S;
    }
 
    // Driver Code
    public static void Main()
    {
        string[] words
            = {  "i", "like", "this", "program", "very", "much" };
 
        string a = RevString(words, words.Length);
 
        Console.WriteLine(a);
    }
}
 
// This code is contributed by Aarti_Rathi and
// shivanisinghss2110


Javascript




<script>
 
// Javascript code to reverse a string
 
// Reverse the string
function RevString(s, l)
{
     
    // Check if number of words is even
    if (l % 2 == 0)
    {
 
        // Find the middle word
        let j = parseInt(l / 2, 10);
 
        // Starting from the middle
        // start swapping words at
        // jth position and l-1-j position
        while (j <= l - 1)
        {
            let temp;
            temp = s[l - j - 1];
            s[l - j - 1] = s[j];
            s[j] = temp;
            j += 1;
        }
    }
 
    // Check if number of words is odd
    else
    {
 
        // Find the middle word
        let j = parseInt((l / 2), 10) + 1;
 
        // Starting from the middle start
        // swapping the words at jth
        // position and l-1-j position
        while (j <= l - 1)
        {
            let temp;
            temp = s[l - j - 1];
            s[l - j - 1] = s[j];
            s[j] = temp;
            j += 1;
        }
    }
 
    let S = s[0];
 
    // Return the reversed sentence
    for(let i = 1; i < 9; i++)
    {
        S = S + " " + s[i];
    }
    return S;
}
 
// Driver code
let s = "i like this program very much";
             
let words = [  "i", "like", "this", "program", "very much"];
   
document.write(RevString(words, 9));
 
// This code is contributed by suresh07
     
</script>


Output

much very program this like i



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

Reverse words in a given string using constant space:

Follow the below steps to solve the problem:

  • Go through the string and mirror each word in the string, 
  • Then, in the end, mirror the whole string.

Below is the implementation of the above approach:

C++




// C++ code for the above approach
 
#include <bits/stdc++.h>
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 (i > left && s[left] == ' ')
            left = i;
 
        i++;
    }
    reverse(s.begin(), s.end());
    return s;
}
 
// Driver code
int main()
{
 
    string str = "i like this program very much";
 
    str = reverse_words(str);
 
    cout << str;
 
    return 0;
}


Java




// Java code for the above approach
 
import java.io.*;
 
class GFG {
   
    // Java does not have built-in swap function to swap
    // characters of a string
    public static String swap(String str, int i, int j)
    {
        char ch[] = str.toCharArray();
        char temp = ch[i];
        ch[i] = ch[j];
        ch[j] = temp;
        return new String(ch);
    }
 
    public 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 < j)
                    s = swap(s, left++, j--);
 
                left = i + 1;
            }
            if (i > left && s.charAt(left) == ' ')
                left = i;
 
            i++;
        }
       
        // Use StringBuilder ".reverse()" method to reverse
        // the whole string.
        s = new StringBuilder(s).reverse().toString();
        return s;
    }
   
    // Driver Code
    public static void main(String[] args)
    {
        String str
            = "i like this program very much";
        str = reverse_words(str);
        System.out.println(str);
    }
}
// This code is contributed by KaaL-EL.


Python3




# Python code for the above approach
 
def reverse_words(s):
    left = 0
    i = 0
    s = list(s)
    n = len(s)
     
    while(s[i] == ' '):
        i = i+1
         
    left = i
     
    while(i < n):
        if(i+1 == n or s[i] == ' '):
            j = i-1
            if i+1 == n:
                j = j+1
             
            while left < j:
                s[left], s[j] = s[j], s[left]
                left = left+1
                j = j-1
             
            left = i + 1
         
        if(i > left and s[left] == ' '):
            left = i
         
        i = i+1
    s = ''.join(s)
    s = s[::-1]
    return s
 
s1 = "i like this program very much"
s1 = reverse_words(s1)
print(s1)
     
# This Code is contributed by Yash Agarwal(yashagarwal2852002)


C#




// C# code to implement the approach
 
using System;
 
class GFG {
 
    public static string swap(string str, int i, int j)
    {
        char[] ch = str.ToCharArray();
        char temp = ch[i];
        ch[i] = ch[j];
        ch[j] = temp;
        return new String(ch);
    }
 
    public static 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++;
 
                while (left < j)
                    s = swap(s, left++, j--);
 
                left = i + 1;
            }
            if (i > left && s[left] == ' ')
                left = i;
 
            i++;
        }
 
        char[] charArray = s.ToCharArray();
        Array.Reverse(charArray);
        return new string(charArray);
    }
 
    // Driver Code
    public static void Main(string[] args)
    {
        string str = "i like this program very much";
        str = reverse_words(str);
        Console.WriteLine(str);
    }
}
// This code is contributed by karandeep1234


Javascript




function swap(s,a,b)
{
    let charArray = [...s];
    let temp = s[a];
    charArray[a] = s[b];
    charArray[b] = temp;
    return charArray.join("");
}
 
// Function to reverse string
function reverse(str) {
    let charArray = [...str];
    let ans = "";
    for(let i=charArray.length-1;i>=0;i--)
    {
        ans+=charArray[i];
    }
    return ans;
 }
 
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++;
 
            while (left < j)
            {
                s = swap(s,left++, j--);
            }
                 
 
            left = i + 1;
        }
        if (i > left && s[left] == ' ')
            left = i;
 
        i++;
    }
    s = reverse(s);
    return s;
}
 
let str = "i like this program very much";
 
str = reverse_words(str);
 
console.log(str);
 
// This code is contributed by akashish__


Output

much very program this like i



Time complexity: O(N)
Auxiliary Space: O(1)

Reverse words in a given string using constant space: using the slicing method and join functions:

Below is the implementation of the above approach:

C++




#include<bits/stdc++.h>
using namespace std;
 
int main() {
    string text = "i like this program very much";
    vector<string> str;
    istringstream iss(text);
    for (string s; iss >> s;) {
        str.push_back(s);
    }
    reverse(str.begin(), str.end());
    cout << str[0];
    for (int i = 1; i < str.size(); i++) {
        cout << " " << str[i];
    }
    return 0;
}
// contributed by akashish__


Java




// Java code for the above approach
 
import java.util.*;
 
class GFG {
    public static void main(String[] args)
    {
        String text
            = "i like this program very much";
        String str[] = text.split(" ");
        Collections.reverse(Arrays.asList(str));
        System.out.println(String.join(" ", str));
    }
}


Python3




# python code to reverse words in a given string
 
# input string
string = "i like this program very much"
 
# spliting words in the given string
# using slicing reverse the words
s = string.split()[::-1]
 
# joining the reversed string and
# printing the output
print(" ".join(s))


C#




using System;
using System.Linq;
public class GFG {
    static public void Main()
    {
        string text
            = "i like this program very much";
        Console.WriteLine(
            string.Join(" ", text.Split(' ').Reverse()));
    }
}
 
// this code is contributed by gangarajula laxmi


Javascript




// Javascript code for the above approach
 
        let text= "i like this program very much";
        let str = text.split(" ");
        str.reverse();
        str = str.join(" ");
        console.log(str);
 
// This code is contributed by garg28harsh.


PHP




<?php
$string = "i like this program very much";
$array = explode(" ", $string);
$rarray = array_reverse($array);
  
echo $newstring = implode(" ", $rarray);
  
// this code is contributed by gangarajula laxmi
?>


Output

much very program this like i



Time complexity: O(N2)
Auxiliary Space: O(N)

Approach: Without splitting the string

By this approach, we can even remove extra trailing spaces and in between the words also.

Basically, this algorithm involves 3 steps.

If you find white space, there can be two possibilities. 
It might be end of a word or else extra trailing space in between the words.
if it is not a white space, add the character to temporary word as shown in the below code.

C++




//C++ code to reverse a string
//without splitting.
#include <iostream>
#include <string>
 
using namespace std;
 
string reverseString(string s)
{
    string ans = "";
    string temp = "";
    for (int i = 0; i < s.length(); i++)
    {
        char ch = s[i];
        if (ch == ' ')
        {
            if (temp != "")
            {
                ans = temp + " " + ans;
            }
            temp = "";
        }
        else
        {
            temp += ch;
        }
    }
    if (temp != "")
    {
        ans = temp + " " + ans;
    }
    if (ans.length() > 0 && ans[ans.length() - 1] == ' ')
    {
        ans = ans.substr(0, ans.length() - 1);
    }
    return ans;
}
 
int main()
{
    string s1 = " Welcome to Geeks For Geeks ";
    cout << "Before reversing length of string : "
         << s1.length() << endl;
    string ans1 = reverseString(s1);
    cout << "After reversing length of string : "
         << ans1.length() << endl;
    cout << "\"" << ans1 << "\"" << endl;
 
    string s2 = " I Love C++ Programming     ";
    cout << "Before reversing length of string : "
         << s2.length() << endl;
    string ans2 = reverseString(s2);
    cout << "After reversing length of string : "
         << ans2.length() << endl;
    cout << "\"" << ans2 << "\"" << endl;
 
    return 0;
}


Java




import java.util.*;
 
class GFG {
     
    public static String reverseString(String s)
    {
        StringBuilder ans=new StringBuilder();
         
        String temp = "";
        for(int i=0;i<s.length();i++)
        {
            char ch = s.charAt(i);
            if(ch==' ')
            {
                //if we find white space add temp in the start
                if(!temp.equals(""))
                {
                    //adding in the front every time
                    ans.insert(0,temp+" ");
                }
                 
                temp = "";
            }
            else
                temp += ch;
        }
     
        //just removing the extra space at the end of the ans
        return ans.toString().substring(0,ans.length()-1);
         
    }
     
    public static void main(String[] args) {
         
        String s1=" Welcome to Geeks For Geeks ";
        System.out.println("Before reversing length of string : "+s1.length());
        String ans1=reverseString(s1);
        System.out.println("After reversing length of string : "+ans1.length());
        System.out.println("\""+ans1+"\"\n");
         
        String s2=" I Love Java   Programming     ";
        System.out.println("Before reversing length of string : "+s2.length());
        String ans2=reverseString(s2);
        System.out.println("After reversing length of string : "+ans2.length());
        System.out.println("\""+ans2+"\"");
         
    }
}
//This code is contributed by aeroabrar_31


Python3




def reverseString(s):
    ans = ""
    temp = ""
    for ch in s:
        if ch == ' ':
            if temp:
                ans = temp + " " + ans
            temp = ""
        else:
            temp += ch
 
    if temp:
        ans = temp + " " + ans
 
    if ans and ans[-1] == ' ':
        ans = ans[:-1]
 
    return ans
 
if __name__ == "__main__":
    s1 = " Welcome to Geeks For Geeks "
    print("Before reversing length of string:", len(s1))
    ans1 = reverseString(s1)
    print("After reversing length of string:", len(ans1))
    print("\"" + ans1 + "\"")
 
    s2 = " I Love Python Programming     "
    print("Before reversing length of string:", len(s2))
    ans2 = reverseString(s2)
    print("After reversing length of string:", len(ans2))
    print("\"" + ans2 + "\"")


C#




using System;
 
class GFG {
     
    public static string ReverseString(string s)
    {
        var ans = new System.Text.StringBuilder();
         
        var temp = "";
        for(var i=0;i<s.Length;i++)
        {
            var ch = s[i];
            if(ch==' ')
            {
                //if we find white space add temp in the start
                if(!temp.Equals(""))
                {
                    //adding in the front every time
                    ans.Insert(0,temp+" ");
                }
                 
                temp = "";
            }
            else
                temp += ch;
        }
     
        //just removing the extra space at the end of the ans
        return ans.ToString().Substring(0,ans.Length-1);
         
    }
     
    public static void Main(string[] args) {
         
        var s1=" Welcome to Geeks For Geeks ";
        Console.WriteLine("Before reversing length of string : "+s1.Length);
        var ans1=ReverseString(s1);
        Console.WriteLine("After reversing length of string : "+ans1.Length);
        Console.WriteLine("\""+ans1+"\"\n");
         
        var s2=" I Love Java   Programming     ";
        Console.WriteLine("Before reversing length of string : "+s2.Length);
        var ans2=ReverseString(s2);
        Console.WriteLine("After reversing length of string : "+ans2.Length);
        Console.WriteLine("\""+ans2+"\"");
         
    }
}


Javascript




// JavaScript code to reverse a string
// without splitting.
function reverseString(s) {
    let ans = ""; // Initialize the result string
    let temp = ""; // Temporary string to build words
    for (let i = 0; i < s.length; i++) {
        let ch = s[i];
        if (ch === ' ') { // If a space is encountered, add the temporary word to the result
            if (temp !== "") {
                ans = temp + " " + ans;
            }
            temp = ""; // Reset the temporary word
        } else {
            temp += ch; // Build the temporary word
        }
    }
    if (temp !== "") { // If there's a leftover word, add it to the result
        ans = temp + " " + ans;
    }
    if (ans.length > 0 && ans[ans.length - 1] === ' ') {
        ans = ans.substring(0, ans.length - 1); // Remove trailing space if present
    }
    return ans; // Return the reversed string
}
 
// Testing the reverseString function
let s1 = " Welcome to Geeks For Geeks ";
console.log("Before reversing length of string : " + s1.length);
let ans1 = reverseString(s1);
console.log("After reversing length of string : " + ans1.length);
console.log("\"" + ans1 + "\"");
 
let s2 = " I Love JavaScript Programming     ";
console.log("Before reversing length of string : " + s2.length);
let ans2 = reverseString(s2);
console.log("After reversing length of string : " + ans2.length);
console.log("\"" + ans2 + "\"");


Output

Before reversing length of string : 28
After reversing length of string : 26
"Geeks For Geeks to Welcome"

Before reversing length of string : 31
After reversing length of string : 23
"Programming Java Love I"



Time Complexity: O(N) where N is length of string

Auxiliary Space: O(1) 

Please write comments if you find any bug in the above code/algorithm, or find other ways to solve the same problem.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads