Reverse words in a given string solution in c++
Sure! Here is a C++ solution to reverse the words in a given string, along with explanations for each step:
#include <iostream>
#include <string>
#include <algorithm>
#include <sstream>
void reverseWords(std::string& str) {
// Reverse the entire string
std::reverse(str.begin(), str.end());
// Reverse each word separately
std::istringstream iss(str);
std::string word;
std::string reversedStr;
while (iss >> word) {
std::reverse(word.begin(), word.end());
reversedStr += word + " ";
}
// Remove the trailing space
if (!reversedStr.empty()) {
reversedStr.pop_back();
}
// Update the original string with the reversed words
str = reversedStr;
}
int main() {
std::string str = "Hello World!";
// Call the function to reverse the words
reverseWords(str);
// Print the reversed string
std::cout << str << std::endl;
return 0;
}
Explanation:
First, we include necessary header files:
<iostream>
for input/output,<string>
for string manipulation,<algorithm>
for thestd::reverse
function, and<sstream>
for string stream operations.The
reverseWords
function takes a reference to a string as a parameter. This function will reverse the words in the given string.Inside the
reverseWords
function, we start by reversing the entire string using thestd::reverse
function. This will reverse the order of all characters in the string.Next, we create an
std::istringstream
object namediss
using the reversed string. This object will allow us to extract individual words from the string.We declare two strings:
word
to store each word extracted from the string, andreversedStr
to store the final reversed string.We enter a
while
loop that continues as long as there are words to be extracted from theiss
object.Inside the loop, we extract the next word from the
iss
object and store it in theword
variable.We then reverse the order of characters in
word
using thestd::reverse
function.We append the reversed
word
to thereversedStr
string, followed by a space.After the loop, we check if
reversedStr
is not empty. If it's not empty, we remove the trailing space by callingpop_back()
.Finally, we update the original string
str
with the reversed words by assigningreversedStr
to it.In the
main
function, we declare a string variablestr
and initialize it with the value "Hello World!".We call the
reverseWords
function, passingstr
as an argument, to reverse the words in the string.Finally, we print the reversed string using
std::cout
.
This program will output the reversed string "olleH !dlroW".
I hope this explanation helps! Let me know if you have any further questions.