Write a program to reverse word in given string.

Given a string of sentence we have to reverse each word of sentence and print the resultant string.


input: i love geeksprep.
output geeksprep love i


step 1- store each word in vector of string.
step 2-iterate the vector in reverse order.

using namespace std;
int main()
string s="i loves geeksprep";
 string k=" ";
for(int i=0;i<s.length();i++)
    if(s[i]!=' ')//if s[i] is not space then add s[i] value to k
    v.push_back(k);//if space come then  push string into vector
    k="";//initialise k again
v.push_back(k);///push the last element
for(int i=v.size()-1;i>=0;i--)
    cout<<v[i]<<" ";

geeksprep love i

Time Complexity:O(N)

Space Complexity:O(N)

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top