Reverse words in a string
Last Updated :
18 Mar, 2025
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.program.very.much"
Output: str = "much.very.program.this.like.i"
Explanation:The words in the input string are reversed while maintaining the dots as separators, resulting in "much.very.program.this.like.i"
.
Input: str = ”..geeks..for.geeks.”
Output: str = “geeks.for.geeks”
Input: str = "...home......"
Output: str = "home"
[Naive Approach] Using Stack - O(n) Time and O(n) Space
Push all words separated by dots into a stack, then pop each word one by one and append it back to form the reversed string.
C++
#include <bits/stdc++.h>
using namespace std;
string reverseWords(string str) {
stack<string> st;
string s = "";
for (int i = 0; i < str.length(); i++) {
if (str[i] != '.') {
s += str[i];
}
// If we see a dot, we push the
// previously seen word into the stack.
else if (!s.empty()) {
st.push(s);
s = "";
}
}
// Last word remaining, add it to stack
if (!s.empty()) {
st.push(s);
}
s = "";
// Now add from top to bottom of the stack
while (!st.empty()) {
s += st.top();
st.pop();
if (!st.empty()) {
s += ".";
}
}
return s;
}
int main() {
string s = "..geeks..for.geeks.";
cout << reverseWords(s) << endl;
return 0;
}
Java
import java.util.Stack;
class GfG {
static String reverseWords(String str) {
Stack<String> stack = new Stack<>();
StringBuilder word = new StringBuilder();
// Iterate through the string
for (int i = 0; i < str.length(); i++) {
// If not a dot, build the current word
if (str.charAt(i) != '.') {
word.append(str.charAt(i));
}
// If we see a dot, push the word into the stack
else if (word.length() > 0) {
stack.push(word.toString());
word.setLength(0);
}
}
// Last word remaining, push it to stack
if (word.length() > 0) {
stack.push(word.toString());
}
// Rebuild the string from the stack
StringBuilder result = new StringBuilder();
while (!stack.isEmpty()) {
result.append(stack.pop());
if (!stack.isEmpty()) {
result.append(".");
}
}
return result.toString();
}
public static void main(String[] args) {
String str = "..geeks..for.geeks.";
System.out.println(reverseWords(str));
}
}
Python
def reverse_words(str):
stack = []
word = ""
# Iterate through the string
for ch in str:
# If not a dot, build the current word
if ch != '.':
word += ch
# If we see a dot, push the word into the stack
elif word:
stack.append(word)
word = ""
# Last word remaining, push it to stack
if word:
stack.append(word)
# Rebuild the string from the stack
return ".".join(stack[::-1])
if __name__ == "__main__":
str = "..geeks..for.geeks."
print(reverse_words(str))
C#
using System;
using System.Collections.Generic;
class GfG {
static string ReverseWords(string str) {
Stack<string> stack = new Stack<string>();
string word = "";
// Iterate through the string
for (int i = 0; i < str.Length; i++) {
// If not a dot, build the current word
if (str[i] != '.') {
word += str[i];
}
// If we see a dot, push the word into the stack
else if (word.Length > 0) {
stack.Push(word);
word = "";
}
}
// Last word remaining, push it to stack
if (word.Length > 0) {
stack.Push(word);
}
// Rebuild the string from the stack
string result = "";
while (stack.Count > 0) {
result += stack.Pop();
if (stack.Count > 0) {
result += ".";
}
}
return result;
}
static void Main() {
string str = "..geeks..for.geeks.";
Console.WriteLine(ReverseWords(str));
}
}
JavaScript
function reverseWords(str) {
let stack = [];
let word = "";
// Iterate through the string
for (let i = 0; i < str.length; i++) {
// If not a dot, build the current word
if (str[i] != '.') {
word += str[i];
}
// If we see a dot, push the word into the stack
else if (word.length > 0) {
stack.push(word);
word = "";
}
}
// Last word remaining, push it to stack
if (word.length > 0) {
stack.push(word);
}
// Rebuild the string from the stack
return stack.reverse().join('.');
}
let str = "..geeks..for.geeks.";
console.log(reverseWords(str));
[Expected Approach] Using Two Pointer - O(n) Time and O(1) Space
Reverse the entire string, then iterate through it to extract words separated by dots. Reverse each word individually and update the original string until the end is reached. Refer to the figure to understand better...
C++
// C++ program to reverse words in a string
#include <bits/stdc++.h>
using namespace std;
string reverseWords(string str) {
// reverse the whole string
reverse(str.begin(), str.end());
int n = str.size();
int i = 0;
for (int l = 0; l < n; ++l) {
if (str[l] != '.') {
// go to the beginning of the word
if (i != 0) str[i++] = '.';
// go to the end of the word
int r = l;
while (r < n && str[r] != '.') str[i++] = str[r++];
// reverse the word
reverse(str.begin() + i - (r - l), str.begin() + i);
// move to the next word
l = r;
}
}
str.erase(str.begin() + i, str.end());
return str;
}
int main() {
string str = "..geeks..for.geeks.";
cout << reverseWords(str) << endl;
return 0;
}
C
// C program to reverse words in a string
#include <stdio.h>
#include <string.h>
// Function to reverse a string
void reverse(char* begin, char* end) {
char temp;
while (begin < end) {
temp = *begin;
*begin++ = *end;
*end-- = temp;
}
}
// Function to reverse words in a string
char* reverseWords(char* str) {
// reverse the whole string
reverse(str, str + strlen(str) - 1);
int n = strlen(str);
int i = 0;
for (int l = 0; l < n; ++l) {
if (str[l] != '.') {
// go to the beginning of the word
if (i != 0) str[i++] = '.';
// go to the end of the word
int r = l;
while (r < n && str[r] != '.') str[i++] = str[r++];
// reverse the word
reverse(str + i - (r - l), str + i - 1);
// move to the next word
l = r;
}
}
str[i] = '\0';
return str;
}
int main() {
char str[] = "..geeks..for.geeks.";
printf("%s\n", reverseWords(str));
return 0;
}
Java
// Java program to reverse words in a string
import java.util.*;
class GfG {
static String reverseWords(String str) {
// Convert the string to mutable StringBuilder
StringBuilder s = new StringBuilder(str);
// Reverse the whole string
s.reverse();
int n = s.length();
int i = 0;
for (int l = 0; l < n; ++l) {
if (s.charAt(l) != '.') {
// go to the beginning of the word
if (i != 0) s.setCharAt(i++, '.');
// go to the end of the word
int r = l;
while (r < n && s.charAt(r) != '.') {
s.setCharAt(i++, s.charAt(r++));
}
// reverse the word
int start = i - (r - l);
int end = i - 1;
while (start < end) {
char temp = s.charAt(start);
s.setCharAt(start, s.charAt(end));
s.setCharAt(end, temp);
start++;
end--;
}
// move to the next word
l = r;
}
}
return s.substring(0, i);
}
public static void main(String[] args) {
String str = "..geeks..for.geeks.";
System.out.println(reverseWords(str));
}
}
Python
# Python program to reverse words in a string
def reverseWords(s):
# reverse the whole string
s = s[::-1]
n = len(s)
i = 0
result = []
l = 0
while l < n:
if s[l] != '.':
# go to the beginning of the word
if i != 0:
result.append('.')
i += 1
# go to the end of the word
r = l
while r < n and s[r] != '.':
result.append(s[r])
i += 1
r += 1
# reverse the word
result[i - (r - l):i] = reversed(result[i - (r - l):i])
# move to the next word
l = r
l += 1
return ''.join(result)
if __name__ == "__main__":
s = "..geeks..for.geeks."
print(reverseWords(s))
C#
// C# program to reverse words in a string
using System;
class GfG {
static void Reverse(char[] str, int start, int end) {
while (start < end) {
char temp = str[start];
str[start] = str[end];
str[end] = temp;
start++;
end--;
}
}
static string ReverseWords(string str) {
// Convert the string to a char array
char[] s = str.ToCharArray();
// reverse the whole string
Reverse(s, 0, s.Length - 1);
int n = s.Length;
int i = 0;
for (int l = 0; l < n; ++l) {
if (s[l] != '.') {
// go to the beginning of the word
if (i != 0) s[i++] = '.';
// go to the end of the word
int r = l;
while (r < n && s[r] != '.') s[i++] = s[r++];
// reverse the word
Reverse(s, i - (r - l), i - 1);
// move to the next word
l = r;
}
}
return new String(s, 0, i);
}
static void Main(string[] args) {
string str = "..geeks..for.geeks.";
Console.WriteLine(ReverseWords(str));
}
}
JavaScript
// JavaScript program to reverse words in a string
function reverse(str, start, end) {
while (start < end) {
let temp = str[start];
str[start] = str[end];
str[end] = temp;
start++;
end--;
}
}
function reverseWords(str) {
// Convert the string to an array of characters
str = str.split('');
// reverse the whole string
reverse(str, 0, str.length - 1);
let n = str.length;
let i = 0;
for (let l = 0; l < n; ++l) {
if (str[l] !== '.') {
// go to the beginning of the word
if (i !== 0) str[i++] = '.';
// go to the end of the word
let r = l;
while (r < n && str[r] !== '.') str[i++] = str[r++];
// reverse the word
reverse(str, i - (r - l), i - 1);
// move to the next word
l = r;
}
}
return str.slice(0, i).join('');
}
let str = "..geeks..for.geeks.";
console.log(reverseWords(str));
[Alternate Approach] Using inbuilt library functions - O(n) Time and O(n) Space
We can efficiently solve this problem using built-in library functions like split
to break the string into words, reverse
to reverse the order of words, and stringstream
(or equivalent functions) to reconstruct the final reversed string. This approach simplifies implementation and improves readability.
C++
#include <bits/stdc++.h>
using namespace std;
string reverseWords(string str) {
// Split the input string by '.' while
// ignoring multiple consecutive dots
vector<string> words;
stringstream ss(str);
string word;
while (getline(ss, word, '.')) {
if (!word.empty()) {
// Ignore empty words caused by multiple dots
words.push_back(word);
}
}
// Reverse the words
reverse(words.begin(), words.end());
// Join the reversed words back into a string
string result;
for (int i = 0; i < words.size(); ++i) {
if (i > 0) {
result += '.';
}
result += words[i];
}
return result;
}
int main() {
string str = "..geeks..for.geeks.";
cout << reverseWords(str) << endl;
return 0;
}
Java
import java.util.*;
class GfG {
static String reverseWords(String str) {
// Split the input string by '.' while
// ignoring multiple consecutive dots
List<String> words = new ArrayList<>();
String[] parts = str.split("\\.");
for (String word : parts) {
if (!word.isEmpty()) {
// Ignore empty words caused by multiple dots
words.add(word);
}
}
// Reverse the words
Collections.reverse(words);
// Join the reversed words back into a string
return String.join(".", words);
}
public static void main(String[] args) {
String str = "..geeks..for.geeks.";
System.out.println(reverseWords(str));
}
}
Python
def reverse_words(str):
# Split the input string by '.' while
# ignoring multiple consecutive dots
words = [word for word in str.split('.') if word]
# Reverse the words
words.reverse()
# Join the reversed words back into a string
return '.'.join(words)
if __name__ == "__main__":
str = "..geeks..for.geeks."
print(reverse_words(str))
C#
using System;
using System.Collections.Generic;
class GfG {
static string ReverseWords(string str) {
// Split the input string by '.' while
// ignoring multiple consecutive dots
List<string> words = new List<string>();
string[] parts = str.Split('.');
foreach (string word in parts) {
if (!string.IsNullOrEmpty(word)) {
// Ignore empty words caused by multiple dots
words.Add(word);
}
}
// Reverse the words
words.Reverse();
// Join the reversed words back into a string
return string.Join(".", words);
}
static void Main(string[] args) {
string str = "..geeks..for.geeks.";
Console.WriteLine(ReverseWords(str));
}
}
JavaScript
function reverseWords(str) {
// Split the input string by '.' while
// ignoring multiple consecutive dots
let words = str.split('.').filter(word => word);
// Reverse the words
words.reverse();
// Join the reversed words back into a string
return words.join('.');
}
let str = "..geeks..for.geeks.";
console.log(reverseWords(str));
Similar Reads
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
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 simp
10 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
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
PHP Reverse a String Reversing a string in PHP refers to rearranging a given string's characters in reverse order, starting from the last character to the first. This task is often used in text manipulation or algorithm challenges, highlighting PHP's string-handling capabilities.Examples: Input : GeeksforGeeksOutput : s
3 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
Easiest Way to Reverse a String Have you wondered which is the easiest way to reverse a string, Imagine you are giving a contest and an algorithm you have made requires reversing a string, you must be aware of the easiest way to reverse a string. What is a reversal of string:Reversing a string is the technique that reverses or cha
4 min read
Reverse a String â Complete Tutorial Given a string s, the task is to reverse the string. Reversing a string means rearranging the characters such that the first character becomes the last, the second character becomes second last and so on.Examples:Input: s = "GeeksforGeeks"Output: "skeeGrofskeeG"Explanation : The first character G mo
13 min read
Reverse a String using Stack Given a string str, the task is to reverse it using stack. Example:Input: s = "GeeksQuiz"Output: ziuQskeeGInput: s = "abc"Output: cbaAlso read: Reverse a String â Complete Tutorial.As we all know, stacks work on the principle of first in, last out. After popping all the elements and placing them bac
3 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 Rajp
6 min read