C++ Program to Reverse Words in a String
Use C++ code like
std::istringstream iss(str); std::vector words; while (iss >> word) words.push_back(word); std::reverse(words.begin(), words.end()); to split the string into words, reverse their order, and join them back.Examples
Inputhello world
Outputworld hello
InputC++ is fun
Outputfun is C++
Inputsingle
Outputsingle
How to Think About It
To reverse words in a string, first split the string into individual words by spaces. Then reverse the order of these words. Finally, join the reversed words back into a single string separated by spaces.
Algorithm
1
Get the input string.2
Split the string into words using spaces as separators.3
Reverse the order of the words.4
Join the reversed words into a single string separated by spaces.5
Return or print the reversed string.Code
cpp
#include <iostream> #include <sstream> #include <vector> #include <algorithm> int main() { std::string str = "C++ is fun"; std::istringstream iss(str); std::vector<std::string> words; std::string word; while (iss >> word) { words.push_back(word); } std::reverse(words.begin(), words.end()); for (size_t i = 0; i < words.size(); ++i) { std::cout << words[i]; if (i != words.size() - 1) std::cout << " "; } std::cout << std::endl; return 0; }
Dry Run
Let's trace the input "C++ is fun" through the code.
1
Input string
str = "C++ is fun"
2
Split into words
words = ["C++", "is", "fun"]
3
Reverse words
words = ["fun", "is", "C++"]
4
Join and print
Output: "fun is C++"
| Iteration | word | words vector |
|---|---|---|
| 1 | C++ | ["C++"] |
| 2 | is | ["C++", "is"] |
| 3 | fun | ["C++", "is", "fun"] |
Why This Works
Step 1: Splitting the string
Using std::istringstream and extraction operator >> splits the string into words separated by spaces.
Step 2: Reversing the words
The std::reverse function reverses the order of words in the vector.
Step 3: Joining and printing
A loop prints the reversed words separated by spaces to form the final reversed string.
Alternative Approaches
Using stack
cpp
#include <iostream> #include <sstream> #include <stack> int main() { std::string str = "hello world"; std::istringstream iss(str); std::stack<std::string> stk; std::string word; while (iss >> word) { stk.push(word); } while (!stk.empty()) { std::cout << stk.top(); stk.pop(); if (!stk.empty()) std::cout << " "; } std::cout << std::endl; return 0; }
Uses a stack to reverse words, which is intuitive but may use more memory than vector reverse.
In-place reversal of characters
cpp
#include <iostream> #include <algorithm> #include <string> void reverseWords(std::string &s) { std::reverse(s.begin(), s.end()); size_t start = 0, end = 0; while ((end = s.find(' ', start)) != std::string::npos) { std::reverse(s.begin() + start, s.begin() + end); start = end + 1; } std::reverse(s.begin() + start, s.end()); } int main() { std::string s = "C++ is fun"; reverseWords(s); std::cout << s << std::endl; return 0; }
Reverses entire string then each word to reverse word order in-place, saving extra space.
Complexity: O(n) time, O(n) space
Time Complexity
Splitting the string and reversing the words each take linear time proportional to the string length n.
Space Complexity
Extra space is used to store words in a vector, which can be up to O(n) in size.
Which Approach is Fastest?
In-place reversal uses O(1) extra space but is more complex; vector or stack methods are simpler but use O(n) space.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Vector + reverse | O(n) | O(n) | Simplicity and readability |
| Stack | O(n) | O(n) | Intuitive reversal using LIFO |
| In-place reversal | O(n) | O(1) | Memory efficiency and in-place modification |
Use
std::istringstream to easily split strings by spaces in C++.Forgetting to handle spaces properly and joining words without spaces causes incorrect output.