Open In App

Reverse words in a string

Last Updated : 18 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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));

Output
geeks.for.geeks

[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));

Output
geeks.for.geeks

[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));

Output
geeks.for.geeks


Next Article

Similar Reads