VOOZH about

URL: https://www.geeksforgeeks.org/cpp/program-to-reverse-words-in-a-given-string-in-c/

⇱ Program to reverse words in a given string in C++ - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Program to reverse words in a given string in C++

Last Updated : 12 Jul, 2025

Given a sentence in the form of string str, the task is to reverse each word of the given sentence in C++. 
Examples: 
 

Input: str = "the sky is blue" 
Output: blue is sky the
Input: str = "I love programming" 
Output: programming love I 
 


 

 
 

  1. Reverse the given string str using STL function reverse().
  2. Iterate the reversed string and whenever a space is found reverse the word before that space using the STL function reverse().

Below is the implementation of the above approach:


Output
code this like I

Time Complexity: O(n) 
Auxiliary Space: O(1)

: We can create the reverse() function which is used to reverse the given string. Below are the steps: 
 

  1. Initially reverse each word of the given string str.
  2. Now reverse the whole string to get the resultant string in desired order.

Below is the implementation of the above approach: 


Output
code this like I

Time Complexity: O(n) 
Auxiliary Space: O(1) 

Method 3: Without Using Extra Space

The above task can also be accomplished by splitting and directly swapping the string starting from the middle. As direct swapping is involved, less space is consumed too.


Output
practice of lot a needs coding at good getting

Time Complexity: O(n) 
Auxiliary Space: O(n)

Method 4: Using stringstream and vector

  1. Create a stringstream from the given string.
  2. Create an empty vector to store the words of the sentence.
  3. Read each word from the stringstream and store it in the vector.
  4. Reverse each word in the vector.
  5. Concatenate the reversed words with a space between each word.
  6. Remove the extra space at the end of the concatenated string.
  7. Reverse the entire concatenated string.
  8. Return the reversed sentence.

Output
code this like I

Time complexity is O(n)
Auxiliary space is O(n)

Comment
Article Tags: