Reverse words in a string
Last Updated :
20 Aug, 2024
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.
- Split the given string into an array of words. For example, ” geeks for all” is spitted as {“geeks”, “for”, “all”}
- Reverse the array of words. We get {“all”, “for”, “geeks”}
- 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);
?>
Using Stack
- Push all words separated by a space into a stack.
- Set the string as empty.
- 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);
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.
- We first reverse individual words of the given string. For example if the given string is “geeks for all” would become “skeeg rof lla”
- 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__
Time Complexity: O(n)
Auxiliary Space: O(1)
Please Login to comment...