Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on String
  • Practice String
  • MCQs on String
  • Tutorial on String
  • String Operations
  • Sort String
  • Substring & Subsequence
  • Iterate String
  • Reverse String
  • Rotate String
  • String Concatenation
  • Compare Strings
  • KMP Algorithm
  • Boyer-Moore Algorithm
  • Rabin-Karp Algorithm
  • Z Algorithm
  • String Guide for CP
Open In App
Next Article:
How to Reverse a String in Place in C++?
Next article icon

C++ Program To Reverse Words In A Given String

Last Updated : 17 Aug, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Example: Let the input string be “i like this program very much”. The function should change the string to “much very program this like i”

reverse-words

Examples: 

Input: s = “geeks quiz practice code” 
Output: s = “code practice quiz geeks”

Input: s = “getting good at coding needs a lot of practice” 
Output: s = “practice of lot a needs coding at good getting”

Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution.

Algorithm:  

  • Initially, reverse the individual words of the given string one by one, for the above example, after reversing individual words the string should be “i ekil siht margorp yrev hcum”.
  • Reverse the whole string from start to end to get the desired output “much very program this like i” in the above example.

Below is the implementation of the above approach: 

C++




// C++ program to reverse a string
#include <bits/stdc++.h>
using namespace std;
  
// Function to reverse words
void reverseWords(string s)
{    
    // Temporary vector to store all words
    vector<string> tmp;
    string str = "";
    for (int i = 0; i < s.length(); i++) 
    {        
        // Check if we encounter space 
        // push word(str) to vector
        // and make str NULL
        if (s[i] == ' ') 
        {
            tmp.push_back(str);
            str = "";
        }
  
        // Else add character to 
        // str to form current word
        else
            str += s[i];
    }
    
    // Last word remaining,add it to vector
    tmp.push_back(str);
  
    // Now print from last to first in vector
    int i;
    for (i = tmp.size() - 1; i > 0; i--)
        cout << tmp[i] << " ";
    // Last word remaining,print it
    cout << tmp[0] << endl;
}
  
// Driver Code
int main()
{
    string s = 
    "i like this program very much";
    reverseWords(s);
    return 0;
}
 
 
Output
much very program this like i  

The above code doesn’t handle the cases when the string starts with space. The following version handles this specific case and doesn’t make unnecessary calls to reverse function in the case of multiple spaces in between. Thanks to rka143 for providing this version. 

C++




// C++ program to implement
// the above approach
void reverseWords(char* s)
{
  char* word_begin = NULL;
  
  // temp is for word boundary 
  char* temp = s;
  
  // STEP 1 of the above algorithm 
  while (*temp) 
  {
    /*This condition is to make sure that 
      the string start with valid character 
      (not space) only*/
    if ((word_begin == NULL) && 
        (*temp != ' ')) 
    {
      word_begin = temp;
    }
    if (word_begin && 
       ((*(temp + 1) == ' ') ||
       (*(temp + 1) == ''))) 
    {
      reverse(word_begin, temp);
      word_begin = NULL;
    }
    temp++;
  
  // End of while 
  } 
  
  // STEP 2 of the above algorithm 
  reverse(s, temp - 1);
}
  
// This code is contributed by rutvik_56.
 
 

Time Complexity: O(n) 

Another Approach:

we can do the above task by splitting and saving the string in a reverse manner. 

Below is the implementation of the above approach:

C++




// C++ program to reverse a string
// s = input()
#include <bits/stdc++.h>
using namespace std;
  
// Driver code
int main()
{
    string s[] = {"i", "like", "this", 
                  "program", "very", "much"};
                                          
    string ans = "";
    for (int i = 5; i >= 0; i--) 
    {
        ans += s[i] + " ";
    }
    cout << 
    ("Reversed String:") << endl;
    cout << 
    (ans.substr(0, ans.length() - 1)) << 
     endl;
  
    return 0;
}
// This code is contributed by divyeshrabadiya07.
 
 
Output
Reversed String:  much very program this like i  

Time Complexity: O(n) 

Without using any 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.   

Below is the implementation of the above approach:

C++




// C++ code to reverse a string
#include <bits/stdc++.h>
using namespace std;
  
// Reverse the string
string RevString(string s[], int l)
{    
    // Check if number of words is even
    if (l % 2 == 0)
    {        
        // Find the middle word
        int j = l / 2;
          
        // Starting from the middle
        // start swapping words at 
        // jth position and l-1-j position
        while (j <= l - 1)
        {
            string temp;
            temp = s[l - j - 1];
            s[l - j - 1] = s[j];
            s[j] = temp;
            j += 1;
        }
    }
      
    // Check if number of words is odd
    else
    {        
        // Find the middle word
        int j = (l / 2) + 1;
          
        // Starting from the middle start
        // swapping the words at jth 
        // position and l-1-j position
        while (j <= l - 1) 
        {
            string temp;
            temp = s[l - j - 1];
            s[l - j - 1] = s[j];
            s[j] = temp;
            j += 1;
        }
    }
      
    string S = s[0];
      
    // Return the reversed sentence
    for(int i = 1; i < 9; i++)
    {
        S = S + " " + s[i];
    }
    return S;
}
  
// Driver code
int main()
{
    string s = "getting good at coding "
               "needs a lot of practice";
                 
    string words[] = {"getting", "good", "at", 
                      "coding", "needs", "a", 
                      "lot", "of", "practice"};
       
    cout << RevString(words, 9) << endl;
    return 0;
}
  
// This code is contributed by divyesh072019
 
 
Output
practice of lot a needs coding at good getting  

Another intuitive constant space solution: Go through the string and mirror each word in the string, then, at the end, mirror the whole string.

The following C++ code can handle multiple contiguous spaces.

C++




// C++ program to implement
// the above approach
#include <algorithm>
#include <iostream>
#include <string>
 using namespace std;
   
string reverse_words(string s)
{
    int left = 0, i = 0, n = s.size();
     
    while (s[i] == ' ')
        i++;
     
    left = i;
     
    while (i < n)
    {
        if (i + 1 == n || 
            s[i] == ' ')
        {
            int j = i - 1;
            if (i + 1 == n)
                j++;
             
            while (left < j)
                swap(s[left++], s[j--]);
             
            left = i + 1;
        }
        if (s[left] == ' ' && i > left)
            left = i;
         
        i++;
    }
    reverse(s.begin(), s.end());
    return s;
}
  
// Driver code
int main()
{ 
    string str = 
    "Be a game changer the world is already full of players"; 
    str = reverse_words(str); 
    cout << str;   
    return 0;
}
// This code is contributed by Gatea David
 
 
Output
players of full already is world the changer game a Be

Reverse Words in a String Using Two-Pointer Approach

Approach:

  1. Reverse the entire string.
  2. Reverse each word in the reversed string.

Steps:

  1. Start by taking the input string as s.
  2. Reverse the entire string s using a two-pointer approach.
  3. Initialize two pointers, start and end, both pointing to the first character of the reversed string.
  4. Traverse the string s and when a space is encountered, reverse the word between start and end pointers using a similar two-pointer approach.
  5. Update the start pointer to the next character after the space and the end pointer to the same position as the start pointer.
  6. Repeat step 4 and 5 until the end of the string is reached.
  7. Return the reversed string.

C++




#include <iostream>
#include <string>
using namespace std;
  
void reverseWord(string& s, int start, int end) {
    while (start < end) {
        swap(s[start], s[end]);
        start++;
        end--;
    }
}
  
string reverseString(string s) {
    int start = 0, end = s.length() - 1;
    reverseWord(s, start, end);
  
    start = 0;
    end = 0;
    while (end < s.length()) {
        if (s[end] == ' ') {
            reverseWord(s, start, end - 1);
            start = end + 1;
        }
        end++;
    }
    reverseWord(s, start, end - 1);
    return s;
}
  
int main() {
    string s = "i am omkhar";
    cout << reverseString(s) << endl;
    return 0;
}
 
 
Output
omkhar am i  

Time complexity: O(n), where n is the length of the input string.
Auxiliary space: O(1), the algorithm uses constant space to perform the reverse operation in-place.

Please refer complete article on Reverse words in a given string for more details!



Next Article
How to Reverse a String in Place in C++?
author
kartik
Improve
Article Tags :
  • C++ Programs
  • DSA
  • Strings
  • Accolite
  • Adobe
  • Amazon
  • CBSE - Class 11
  • Cisco
  • Goldman Sachs
  • MakeMyTrip
  • MAQ Software
  • Microsoft
  • Morgan Stanley
  • Paytm
  • Payu
  • Reverse
  • SAP Labs
  • school-programming
  • Wipro
  • Zoho
Practice Tags :
  • Accolite
  • Adobe
  • Amazon
  • Cisco
  • Goldman Sachs
  • MakeMyTrip
  • MAQ Software
  • Microsoft
  • Morgan Stanley
  • Paytm
  • Payu
  • SAP Labs
  • Wipro
  • Zoho
  • Reverse
  • Strings

Similar Reads

  • Program to reverse words in a given string in C++
    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 theInput: str = "I love programming" Output: programming love I Method 1: Using STL functions Reverse the given string str using STL
    6 min read
  • Reverse words in a given string | Set 2
    Given string str, the task is to reverse the string by considering each word of the string, str as a single unit. Examples: Input: str = “geeks quiz practice code”Output: code practice quiz geeks Explanation: The words in the given string are [“geeks”, “quiz”, “practice”, “code”]. Therefore, after r
    9 min read
  • How to Reverse a String in Place in C++?
    In C++, reversing a string is a basic operation in programming that is required in various applications, from simple and complex algorithms. Reversing a string in place involves changing the characters of the string directly without using input-dependent additional storage. In this article, we learn
    2 min read
  • C++ Program to Reverse a String Using Stack
    Given a string, reverse it using stack. For example "GeeksQuiz" should be converted to "ziuQskeeG". Following is simple algorithm to reverse a string using stack. 1) Create an empty stack.2) One by one push all characters of string to stack.3) One by one pop all characters from stack and put them ba
    4 min read
  • Reverse middle words of a string
    Given a string str, print reverse all words except the first and last words. Examples: Input : Hi how are you geeks Output : Hi woh era uoy geeks Input : I am fine Output : I ma finePrint the first word.For remaining middle words, print the reverse of every word after reaching end of it. This will p
    4 min read
  • C++ Program To Print Reverse of a String Using Recursion
    Write a recursive function to print the reverse of a given string. Code:  C/C++ Code // C++ program to reverse a string using recursion #include <bits/stdc++.h> using namespace std; /* Function to print reverse of the passed string */ void reverse(string str) { if(str.size() == 0) { return; }
    2 min read
  • How to Reverse a String in C++?
    Reversing a string means replacing the first character with the last character, second character with the second last character and so on. In this article, we will learn how to reverse a string in C++. Examples Input: str = "Hello World"Output: dlroW olleHExplanation: The last character is replaced
    2 min read
  • How to Reverse a Word Using Stack in C++?
    In C++, we have a stack data structure that follows the Last In First Out (LIFO) principle. In this article, we will learn how to reverse a word using a stack in C++. Example: Input:word = "GeeksforGeeks"Output:Reversed Word: skeeGrofskeeGReverse a String Using Stack in C++To reverse a word using a
    2 min read
  • Split a Sentence into Words in C++
    Write a C++ program to split a given sentence into words. Words are separated by whitespace. Examples: Input: "Geeks for Geeks"Output: "Geeks", "for", "Geeks"Explanation: The sentence is split into words wherever there is a space. Input: "C++ is fun"Output: "C++", "is", "fun"Explanation: The sentenc
    7 min read
  • C++ Program to Print the First Letter of Each Word of a String
    String str is given which contains lowercase English letters and spaces. It may contain multiple spaces. Get the first letter of every word and return the result as a string. The result should not contain any space. Examples: Input: str = "geeks for geeks" Output: gfg Input: str = "happy coding" Out
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences