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:

  1. First, we include necessary header files: <iostream> for input/output, <string> for string manipulation, <algorithm> for the std::reverse function, and <sstream> for string stream operations.

  2. The reverseWords function takes a reference to a string as a parameter. This function will reverse the words in the given string.

  3. Inside the reverseWords function, we start by reversing the entire string using the std::reverse function. This will reverse the order of all characters in the string.

  4. Next, we create an std::istringstream object named iss using the reversed string. This object will allow us to extract individual words from the string.

  5. We declare two strings: word to store each word extracted from the string, and reversedStr to store the final reversed string.

  6. We enter a while loop that continues as long as there are words to be extracted from the iss object.

  7. Inside the loop, we extract the next word from the iss object and store it in the word variable.

  8. We then reverse the order of characters in word using the std::reverse function.

  9. We append the reversed word to the reversedStr string, followed by a space.

  10. After the loop, we check if reversedStr is not empty. If it's not empty, we remove the trailing space by calling pop_back().

  11. Finally, we update the original string str with the reversed words by assigning reversedStr to it.

  12. In the main function, we declare a string variable str and initialize it with the value "Hello World!".

  13. We call the reverseWords function, passing str as an argument, to reverse the words in the string.

  14. 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.