Program to reverse words in a given string in C++
Last Updated :
06 Jul, 2023
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
Method 1: Using STL functions
- Reverse the given string str using STL function reverse().
- 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:
CPP
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to reverse the given string
string reverseString(string str)
{
// Reverse str using inbuilt function
reverse(str.begin(), str.end());
// Add space at the end so that the
// last word is also reversed
str.insert(str.end(), ' ');
int n = str.length();
int j = 0;
// Find spaces and reverse all words
// before that
for (int i = 0; i < n; i++) {
// If a space is encountered
if (str[i] == ' ') {
reverse(str.begin() + j, str.begin() + i);
// Update the starting index
// for next word to reverse
j = i + 1;
}
}
// Remove spaces from the end of the
// word that we appended
str.pop_back();
// Return the reversed string
return str;
}
// Driver code
int main()
{
string str = "I like this code";
// Function call
string rev = reverseString(str);
// Print the reversed string
cout << rev;
return 0;
}
Time Complexity: O(n)
Auxiliary Space: O(1)
Method 2: Without using the inbuilt function: We can create the reverse() function which is used to reverse the given string. Below are the steps:
- Initially reverse each word of the given string str.
- Now reverse the whole string to get the resultant string in desired order.
Below is the implementation of the above approach:
CPP
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function used to reverse a string
// from index l to r
void reversed(string& s, int l, int r)
{
while (l < r) {
// Swap characters at l and r
swap(s[l], s[r]);
l++;
r--;
}
}
// Function to reverse the given string
string reverseString(string str)
{
// Add space at the end so that the
// last word is also reversed
str.insert(str.end(), ' ');
int n = str.length();
int j = 0;
// Find spaces and reverse all words
// before that
for (int i = 0; i < n; i++) {
// If a space is encountered
if (str[i] == ' ') {
// Function call to our custom
// reverse function()
reversed(str, j, i - 1);
// Update the starting index
// for next word to reverse
j = i + 1;
}
}
// Remove spaces from the end of the
// word that we appended
str.pop_back();
// Reverse the whole string
reversed(str, 0, str.length() - 1);
// Return the reversed string
return str;
}
// Driver code
int main()
{
string str = "I like this code";
// Function call
string rev = reverseString(str);
// Print the reversed string
cout << rev;
return 0;
}
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.
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 AJAY MAKVANA
Outputpractice of lot a needs coding at good getting
Time Complexity: O(n)
Auxiliary Space: O(n)
Method 4: Using stringstream and vector
- Create a stringstream from the given string.
- Create an empty vector to store the words of the sentence.
- Read each word from the stringstream and store it in the vector.
- Reverse each word in the vector.
- Concatenate the reversed words with a space between each word.
- Remove the extra space at the end of the concatenated string.
- Reverse the entire concatenated string.
- Return the reversed sentence.
C++
#include <bits/stdc++.h>
using namespace std;
// Function to reverse the words of a sentence
string reverseString(string str)
{
// Creating a stringstream from given string
stringstream ss(str);
// Vector to store the words of the sentence
vector<string> words;
// Temporary variable to store each word
string temp;
// Reading each word from stringstream
// and storing it into vector
while (ss >> temp) {
words.push_back(temp);
}
// Reversing each word of the sentence
for (int i = 0; i < words.size(); i++) {
reverse(words[i].begin(), words[i].end());
}
// Concatenating the reversed words
string rev = "";
for (int i = 0; i < words.size(); i++) {
rev += words[i] + " ";
}
// Removing the extra space at the end
rev.pop_back();
// Reversing the entire sentence
reverse(rev.begin(), rev.end());
// Return the reversed sentence
return rev;
}
// Driver code
int main()
{
string str = "I like this code";
// Function call
string rev = reverseString(str);
// Print the reversed string
cout << rev;
return 0;
}
// Output: "code this like I"
Time complexity is O(n)
Auxiliary space is O(n)
Similar Reads
C++ Program To Reverse Words In A Given String 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" 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 = "p
7 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
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
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
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++ 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; } reverse
2 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
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++.ExamplesInput: str = "Hello World"Output: dlroW olleHExplanation: The last character is replaced by
2 min read
C++ Program to Check if a Given String is Palindrome or Not A string is said to be palindrome if the reverse of the string is the same as the original string. In this article, we will check whether the given string is palindrome or not in C++.ExamplesInput: str = "ABCDCBA"Output: "ABCDCBA" is palindromeExplanation: Reverse of the string str is "ABCDCBA". So,
4 min read
How Do I Iterate Over the Words of a String? In C++, strings are character sequences stored in a char array. It may contain text in the form of multiple words representing a sentence. In this article, we will learn how we can iterate over the words of a string in C++. Example: Input: myString ="Geek for Geeks" Output: Geek for GeeksIterate Ove
2 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