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 = “practice of lot a needs coding at good getting”
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++
#include <bits/stdc++.h>
using namespace std;
void reverseWords(string s)
{
vector<string> tmp;
string str = "" ;
for ( int i = 0; i < s.length(); i++)
{
if (s[i] == ' ' )
{
tmp.push_back(str);
str = "" ;
}
else
str += s[i];
}
tmp.push_back(str);
int i;
for (i = tmp.size() - 1; i > 0; i--)
cout << tmp[i] << " " ;
cout << tmp[0] << endl;
}
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++
void reverseWords( char * s)
{
char * word_begin = NULL;
char * temp = s;
while (*temp)
{
if ((word_begin == NULL) &&
(*temp != ' ' ))
{
word_begin = temp;
}
if (word_begin &&
((*(temp + 1) == ' ' ) ||
(*(temp + 1) == '' )))
{
reverse(word_begin, temp);
word_begin = NULL;
}
temp++;
}
reverse(s, temp - 1);
}
|
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++
#include <bits/stdc++.h>
using namespace std;
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;
}
|
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++
#include <bits/stdc++.h>
using namespace std;
string RevString(string s[], int l)
{
if (l % 2 == 0)
{
int j = l / 2;
while (j <= l - 1)
{
string temp;
temp = s[l - j - 1];
s[l - j - 1] = s[j];
s[j] = temp;
j += 1;
}
}
else
{
int j = (l / 2) + 1;
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];
for ( int i = 1; i < 9; i++)
{
S = S + " " + s[i];
}
return S;
}
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;
}
|
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++
#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;
}
int main()
{
string str =
"Be a game changer the world is already full of players" ;
str = reverse_words(str);
cout << str;
return 0;
}
|
Output
players of full already is world the changer game a Be
Reverse Words in a String Using Two-Pointer Approach
Approach:
- Reverse the entire string.
- Reverse each word in the reversed string.
Steps:
- Start by taking the input string as s.
- Reverse the entire string s using a two-pointer approach.
- Initialize two pointers, start and end, both pointing to the first character of the reversed string.
- Traverse the string s and when a space is encountered, reverse the word between start and end pointers using a similar two-pointer approach.
- Update the start pointer to the next character after the space and the end pointer to the same position as the start pointer.
- Repeat step 4 and 5 until the end of the string is reached.
- 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;
}
|
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!
Last Updated :
17 Aug, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...