> For the complete documentation index, see [llms.txt](https://abhyas-kanaujia.gitbook.io/lb-dsa-notes-and-homework-abhyas/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://abhyas-kanaujia.gitbook.io/lb-dsa-notes-and-homework-abhyas/14-character-array-and-strings/discord-homework/05.-reverse-words-in-a-string-ii.md).

# 05. Reverse words in a string ii

[Link](https://leetcode.com/problems/reverse-words-in-a-string-ii/)

```cpp
#include <bits/stdc++.h>
using namespace std;

int main()
{
  string str = "the sky is blue";

  // reverse the whole string
  reverse(str.begin(), str.end());

  // revere each word
  int i = 0;
  for (int j = 1; j < str.length(); j++)
    if (str[j] == ' ')
    {

      reverse(str.begin() + i, str.begin() + j);
      i = j + 1;
    }

  // reverse the last word
  reverse(str.begin() + i, str.begin() + str.length());

  cout << str << endl;
}
```
