Reverse Words in a String β Explained with STL Magic β¨


π© 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 π
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