Reverse Words in a String – Explained with STL Magic ✨

Abhinav KumarAbhinav Kumar
3 min read

🚩 Problem Statement (Simplified)

Given a string s, reverse the order of words.

  • Words are separated by spaces.

  • Extra spaces (leading, trailing, or multiple) should be removed in the output.

πŸ“₯ Input: " hello world "
πŸ“€ Output: "world hello"


🧠 My Thought Process

At first, I wrote a basic solution using loops and string manipulation. It worked fine, but felt a bit long and messy.

Then, I came across an STL-based way that cleaned things up beautifully. Let's walk through both approaches.


πŸ› οΈ Brute-Force Style (My First Try)

class Solution {
public:
    string reverseWords(string s) {
        int size = s.size(); 
        string temp = "";
        string rev = ""; // to store final reversed string; 
        for(int i = 0; i < size; i++) {
            if(s[i] != ' ') temp += s[i];
            else if(temp != "") {
                if(rev != "") rev = temp + " " + rev;
                else rev = temp; // this will help to store first word without any extra spaces
                temp = "";
            }
        }
        if(temp != "") { // for the last word, as when we will loop through the string s with no space at the end then on that situation else if() won't be checked as only if's condition gets satisfied then it won't check for else if(); 
            if(rev != "") rev = temp + " " + rev;
            else rev = temp;
        }
        return rev;
    }
};

πŸ“Œ How it works:

  • Loop through the string, collect characters into temp.

  • When you hit a space, add the word to rev in reverse order.

  • Handles extra spaces manually.

βœ… It works, but it's manual and not clean.


✨ Clean STL-Based Solution

#include <sstream>
#include <vector>
#include <algorithm>

class Solution {
public:
    string reverseWords(string s) {
        istringstream iss(s);     // Treats string as input stream
        vector<string> words;     // Stores words
        string word;

        while (iss >> word) {     // Auto-splits & skips spaces
            words.push_back(word);
        }

        reverse(words.begin(), words.end());

        string result;
        for (int i = 0; i < words.size(); ++i) {
            result += words[i];
            if (i != words.size() - 1) result += " ";
        }

        return result;
    }
};

🧠 What I Learned (And You Should Too!)

πŸ”Έ istringstream

  • Lets you read from a string like you read from cin.

  • iss >> word reads one word at a time, ignoring extra spaces.

πŸ”Έ vector<string>

  • Stores the words in order. Easy to reverse using STL.

πŸ”Έ reverse()

  • reverse(words.begin(), words.end()) flips the word order in one line!

βœ… Final Output

πŸ“₯ Input: " sky is blue "
πŸ“€ Output: "blue is sky"


🧢 Wrap-Up

This problem helped me understand istringstream betterβ€”it’s now one of my go-to tools for parsing strings cleanly.


keep coding keep optimising πŸš€


0
Subscribe to my newsletter

Read articles from Abhinav Kumar directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Abhinav Kumar
Abhinav Kumar

πŸŽ“ B.Tech CSE | πŸ‘¨β€πŸ’» Learning DSA & C++ | πŸš€ Building projects & writing what I learn | πŸ“š Currently solving LeetCode & exploring Git/GitHub