text: >>
  Reverse Words in a String II in C++
  C in Depth: The Complete C Programming Guide for Beginners
  45 Lectures 4.5 hours
  Practical C++: Learn C++ Basics Step by Step
  50 Lectures 4.5 hours
  Master C and Embedded C Programming- Learn as you go
  66 Lectures 5.5 hours
  Suppose we have one input string, we have to reverse the strings word by word.
  So, if the input is like ["t","h","e"," ","m","a","n"," ","i","s"," ","n","l","c","e"], then the output will be ["n","l","c","e"," ","i","s"," ","m","a","n"," ","t","h","e"]
  To solve this, we will follow these steps −
  reverse the array s
  j := 0
  n := size of s
  for initialize i := 0, when i < n, update (increase i by 1), do −
  if s[i] is same as ' ', then −
  reverse the array s from index j to i
  j := i + 1
  reverse the array s from index j to n
  Example
  Let us see the following implementation to get better understanding −
  #include <bits/stdc++.h> using namespace std; void print_vector(vector<auto< v){ cout << "["; for(int i = 0; i<v.size(); i++){ cout << v[i] << ", "; } cout << "]"<<endl; } class Solution { public: void reverseWords(vector<char>& s) { reverse(s.begin(), s.end()); int j = 0; int n = s.size(); for(int i = 0; i < n; i++){ if(s[i] == ' '){ reverse(s.begin() + j, s.begin() + i); j = i + 1; } } reverse(s.begin() + j, s.begin() + n); } }; main(){ Solution ob; vector<char> v = {'t','h','e',' ','m','a','n',' ','i','s',' ','n','i','c','e'}; ob.reverseWords(v); print_vector(v); }
  Input
  {'t','h','e',' ','m','a','n',' ','i','s',' ','n','i','c','e'}
  Output
  [n, i, c, e, , i, s, , m, a, n, , t, h, e, ]
  - Related Questions & Answers
  - Reverse String II in Python
  - Reverse Words in a String in C++
  - Reverse words in a given String in C#
  - Reverse words in a given String in Java
  - Reverse words in a given String in Python
  - C# program to Reverse words in a string
  - Reverse Linked List II in C++
  - Reverse a string in C#
  - Reverse a string in C/C++
  - String reverse vs reverse! function in Ruby
  - Reversing words in a string in JavaScript
  - Reverse String in Python
  - Reverse the words in the string that have an odd number of characters in JavaScript
  - Reverse all the words of sentence JavaScript
  - Reverse only the odd length words - JavaScript
  Advertisements